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

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

Topic source

def _not_divisible(n): return lambda x: x%n>0

def primes(): yield 2 it=_odd_iter() while True: n=next(it) yield n it=filter(_not_divisible(n), it) 如果改成 it=filter(lambda x: x%n>0, it) 结果就是错的,请问这是什么原因呢?

现在知道了吗

我也很想知道,如果楼主知道了,麻烦到这里来说一下,谢谢

filter参数有一个应该是函数吧,我觉得错误原因在这里

SergioJune

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

filter(lambda x: x % num != 0, it)

我这样写不会报错

def _not_divisible(n): return lambda x: x%n>0 这里面 n 是函数参数,如果这样写 it=filter(lambda x: x%n>0, it) 就变成x是函数参数了

力弹则折

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

你的n是哪来的?

Mark一下,确实也没想明白原因

蓝萨节

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

上面的方法返回的是一个匿名函数,下面是返回值,是不同的

蓝萨节

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

通过一个返回一个函数,实现了对n的闭包,而如果直接是lambda表达式,n的值是变化的


  • 1
  • 2

Reply