Discuss / Python / 关于primes那个函数,为什么不能直接在filter里用lambda呢?

关于primes那个函数,为什么不能直接在filter里用lambda呢?

Topic source

冰冰洁123

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

如题,primes那个函数里,如果把这行代码:

it = filter(_not_divisible(n), it)

改成:

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

那么结果变成: 2 3 5 7 9 11 13 15 17 19 21 23 ... 为什么呢?求大侠赐教啊。。

廖雪峰

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

_not_divisible(n)相当于lambda n: lambda x: x % n > 0

starara

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

廖老师,您好,代码改成您说的这样,出现结果也还是不对呀,依然会出现9,15等合数,这是为什么呀?

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 n:lambda x:x%n>0,it) for n in primes(): if n<100: print(n) else: break

海洋why2013

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

后面的返回函数那一章有说明,是返回函数引用里变量n,但不是立即执行,是在返回的时候n已经变成最后一个值了,所以会有问题。 为了避免这种问题,所以写了_not_divisible(n),调用的时候,就把n固定了。


  • 1

Reply