Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么循环中的列表在过滤后变为空_Python_Python 3.x_Iterator_Python 2.x - Fatal编程技术网

Python 为什么循环中的列表在过滤后变为空

Python 为什么循环中的列表在过滤后变为空,python,python-3.x,iterator,python-2.x,Python,Python 3.x,Iterator,Python 2.x,我正在尝试Python3中的lambda函数。我尝试了以下链接中给出的示例(查找素数): 这在Python3中不起作用 我尝试在筛选后分配相同的全局变量。无法使它工作 变量素数在第一次循环后变为空数组。 有人知道吗 def test1(): num = 50 primes = range(2,num); for i in range(2, 8): print(list(primes)); primes = filter(lambda

我正在尝试Python3中的lambda函数。我尝试了以下链接中给出的示例(查找素数): 这在Python3中不起作用

我尝试在筛选后分配相同的全局变量。无法使它工作

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

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(); 
过滤器
。一旦迭代器耗尽,就像代码中的
list
一样,您就不能重用它

这在Python2.x中起作用的原因是早期版本中的
filter

下面是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))