Discuss / Python / 求讲解我的这种方式,为什么9和15都没有被过滤掉呢?

求讲解我的这种方式,为什么9和15都没有被过滤掉呢?

Topic source

我只不过把老师的一个函数直接写成匿名函数返回了,结果就不一样了,3的倍数都没有被过滤掉,请问大家这是为什么?谢谢了

def _odd_iter(): n=1 while True: n=n+2 yield n

def primes(): yield 2 it = _odd_iter() while True: n=next(it) yield n it = filter(lambda x:x%n>0,it)

for n in primes(): if n<20: print(n) else: break

参数n是匿名函数外的全局变量,改为lambda x,n=n:x%n>0 试试

非常感谢a41415252_6353cc,您的回答完美的解决了困扰我好几天的问题。


  • 1

Reply