Python迭代器的奇怪行为

时间:2013-11-06 01:39:08

标签: python iterator

我正在玩Python生成器和itertools模块,并尝试制作Eratosthenes Sieve的无限版本。这是我的代码:

from itertools import count, ifilter, islice

def sieve_broken():
    candidates = count(start=2)
    while True:
        prime = next(candidates)
        yield prime
        candidates = ifilter(lambda n: n % prime, candidates)

当我测试它时,我明白了:

>>> print list(islice(sieve_broken(), 10))
[2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

但如果我用这样的函数替换candidates的重新分配:

def sieve_fixed():
    def exclude_multiples(factor, numbers):
        return ifilter(lambda n: n % factor, numbers)

    candidates = count(start=2)
    while True:
        prime = next(candidates)
        yield prime
        candidates = exclude_multiples(prime, candidates)

我明白了:

>>> print list(islice(sieve_fixed(), 10))
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]

我无法弄清楚为什么第一个版本不起作用。据我所知,这两个版本应该是等价的。有谁知道为什么他们不一样?

1 个答案:

答案 0 :(得分:4)

你已经成为a very common pitfall when using closures in Python的牺牲品:闭包带有它们的范围,你继续在相同的范围内替换它。

candidates = ifilter(lambda n, prime=prime: n % prime, candidates)