教程里的 def _not_divisible(n): return lambda x: x % n > 0 ……
while True: n = next(it) # 返回序列的第一个数 yield n it = filter(_not_divisible(n), it) # 构造新序列
以上为什么不能直接换成 while True: n=next(it) yield n it =filter(lambda x: x % n > 0 , it ) 呢?
你先试试两种写法运行结果有没有区别
试过换完之后,输出的不是质数,而是之前构造好的所有奇数,不明白filter怎么没有起作用。
你不能直接引用变量n,因为它在后面的循环中随时在变化,必须用函数参数捕获当前的n,复制一份。
_not_divisible(n)的n和循环内部的变量n不一样
_not_divisible(n)
谢谢廖老师解答,明白了,含义的确不一样,不能直接在lambda函数内部调用循环变量n,n都没传进去
Sign in to make a reply
Enola燕玲
教程里的 def _not_divisible(n): return lambda x: x % n > 0 ……
while True: n = next(it) # 返回序列的第一个数 yield n it = filter(_not_divisible(n), it) # 构造新序列
以上为什么不能直接换成 while True: n=next(it) yield n it =filter(lambda x: x % n > 0 , it ) 呢?