Discuss / Python / 关于之前素数那道题的一点疑问

关于之前素数那道题的一点疑问

Topic source

___sunsunsun

#12 Created at ... [Delete] [Delete and Lock User]

你要想这么写,得这样 it = filter(lambda n: lambda x: x % n > 0, it)

fjowinegaegr

#13 Created at ... [Delete] [Delete and Lock User]

可以这样试试,我测试是正确的: it=filter(lambda x,y=n:x%y>0,it) y是lambda定义的局部变量,把n的值传给y,变成y的默认值,同时filter会把列表里的内容传给lambda的x,这样lambda才能访问到n并且参数个数正确 另外一种获得n的值的方法就是廖老师用的闭包

张垚1977

#14 Created at ... [Delete] [Delete and Lock User]

it = list(filter(lambda x: x % n > 0, it))

TheAlakay

#15 Created at ... [Delete] [Delete and Lock User]

楼上上说的很好了,就应该用it=filter(lambda x,y=n:x%y>0,it) 我再补充一点,你这个之所以是错的,是因为此时序列it还不是固定的,生成it的过程中需要用到n,n会变化,从而导致lambda函数失效。

c_jay2016

#16 Created at ... [Delete] [Delete and Lock User]

不会报错啊

夏海56

#17 Created at ... [Delete] [Delete and Lock User]

第一种写法是调用函数,将外部参数n传入了lambda,第二种lambda函数中的n为定义吧

夏海56

#18 Created at ... [Delete] [Delete and Lock User]

为什么结果都是奇数呢

夏海56

#19 Created at ... [Delete] [Delete and Lock User]

直接使用lambda的时候,n为什么是变化的呢,it是实时调用n,实时计算的呀

夏海56

#20 Created at ... [Delete] [Delete and Lock User]

“注意到filter()函数返回的是一个Iterator,也就是一个惰性序列,所以要强迫filter()完成计算结果,需要用list()函数获得所有结果并返回list。” 应该是由于filter返回的是一个惰性序列,不会及时计算,和返回函数很像。

def f1(): i=0 L=[] while i<3: i=i+1 def f2(x): return x*i L.append(f2(2)) return L a=f1() print(a)

#运行结果为[2,4,6]

def f1(): i=0 L=[] while i<3: i=i+1 def f2(x): yield x*i L.append(f2(2)) return L a=f1() print(a)

#运行结果为[<generator object f1.<locals>.f2 at 0x000002B4709EEEB8>, <generator object f1.<locals>.f2 at 0x000002B4709EEFC0>, <generator object f1.<locals>.f2 at 0x000002B4709EEE60>]

def f1(): i=0 L=[] while i<3: i=i+1 def f2(x): yield x*i L.append(f2(2)) return L a,b,c=f1() print(next(a),next(b),next(c))

#运行结果为6 6 6


  • 1
  • 2

Reply