Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.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 3.x 在Python3中筛选筛选出的列表_Python 3.x - Fatal编程技术网

Python 3.x 在Python3中筛选筛选出的列表

Python 3.x 在Python3中筛选筛选出的列表,python-3.x,Python 3.x,我对Python3.x中过滤器函数的行为感到困惑 假设下一个代码: >>> test = [1, 2, 3, 4, 5, 6, 7, 8] >>> for num in range(4): test = filter( lambda x: x != num, test) >>> print(list(test)) # [1, 2, 4, 5, 6, 7, 8] 我认为test变量将包含连续过滤范围(4)中存在的值(nu

我对Python3.x中过滤器函数的行为感到困惑 假设下一个代码:

>>> test = [1, 2, 3, 4, 5, 6, 7, 8]
>>> for num in range(4):
       test = filter( lambda x: x != num, test)
>>> print(list(test))
    # [1, 2, 4, 5, 6, 7, 8]
我认为test变量将包含连续过滤范围(4)中存在的值(num)的结果,但是最终列表根本没有过滤

有人能给我解释一下这种行为吗?如果可能的话,如何得到预期的结果 #[4,5,6,7,8]


注意:我的原始代码没有这段代码简单,但这只是为了说明我发现错误的地方。

问题在于
filter
返回一个filter对象的实例。要使编写的代码正常工作,必须使用filter对象在循环中创建一个新列表

for num in range(4):
    test = list( filter( lambda x: x != num, test) )

问题是
filter
返回迭代器,迭代器不会“冻结”
num
的值,如下代码所示:

>>> test = [1, 2, 3, 4, 5, 6, 7, 8]
>>> for num in range(4):
...     test = filter(lambda x: print(x, '!=', num) or x != num, test)
... 
>>> list(test)
1 != 3
1 != 3
1 != 3
1 != 3
2 != 3
2 != 3
2 != 3
2 != 3
3 != 3
4 != 3
[...]
[1, 2, 4, 5, 6, 7, 8]
如您所见,当
list(test)
并计算迭代器时,只使用
num
的最后一个值

一种解决方案可能是在每次迭代中使用
list(filter(…)
,正如已经提出的那样

但如果您想节省内存,以下是如何“冻结”num:

(当然,这只是一个示例。请尝试使代码更具可读性。)


通常,您需要做的是保留对
num
值的引用,并避免在内部范围内按名称引用它。

过滤器对象仍然包含
测试
中的每个对象。因此,请尝试以下方法:

test = [1, 2, 3, 4, 5, 6, 7, 8]
for num in range(4):
   test = filter( lambda x: x != num, list(test))
print(list(test))
通过将
list
转换为第三行中的
test
,我们可以有效地删除我们不想要的项目:

>>> print(list(test))
[4, 5, 6, 7, 8]
>>>

我刚刚运行了你的代码,它在python2.7上运行得非常好。您确定它在Python3中不起作用吗?
>>> print(list(test))
[4, 5, 6, 7, 8]
>>>