为什么循环里面的list过滤后就变空了

Why does the list inside the loop become empty after filtering

我正在尝试 python 中的 lambda 函数 3. 我尝试了此 link 中给出的示例(以查找素数): http://www.secnetix.de/olli/Python/lambda_functions.hawk 这在 python 3 中不起作用。

我试图在过滤后分配相同的全局变量。无法使其工作。

变量 primes 在第一次循环后变为空数组。 有人知道吗?

def test1():
    num = 50
    primes = range(2,num); 
    for i in range(2, 8): 

        print(list(primes)); 
        primes = filter(lambda x: x % i, primes); 
        print(list(primes), i); 

    print("last"); 
    print(list(primes)); 

test1(); 

filterreturns an iterator。一旦迭代器耗尽,就像您的代码中的 list 一样,您将无法重用它。

这在 Python 2.x 中起作用的原因是因为 filter returned a list 在早期版本中。

下面是 Python 3.

中此行为的一个最小示例
odds = filter(lambda x: x % 2, range(10))

res = list(odds)
print(res)
# [1, 3, 5, 7, 9]

res = list(odds)
print(res)
# []

为了解决这个问题,将列表分配给 primes 而不是迭代器:

primes = list(filter(lambda x: x % i, primes))