This question already has answers here:
List returned by map function disappears after one use
(2个答案)
3年前关闭。
我正在学习如何使用
这是我编写的代码:
如您所见,我正在尝试删除所有不包含
该代码正常工作,实际上如果我这样做:
我得到:
问题是,如果我做两次:
第二次,我得到一个空 list 。
你能解释一下为什么吗?
我应该提到,对于python2,
(2个答案)
3年前关闭。
我正在学习如何使用
filter
函数。这是我编写的代码:
people = [{'name': 'Mary', 'height': 160},
{'name': 'Isla', 'height': 80},
{'name': 'Sam'}]
people2 = filter(lambda x: "height" in x, people)
如您所见,我正在尝试删除所有不包含
'height'
键的字典。该代码正常工作,实际上如果我这样做:
print(list(people2))
我得到:
[{'name': 'Mary', 'height': 160}, {'name': 'Isla', 'height': 80}]
问题是,如果我做两次:
print(list(people2))
print(list(people2))
第二次,我得到一个空 list 。
你能解释一下为什么吗?
最佳答案
这是经典的python3 doh!。
过滤器是可以迭代的特殊可迭代对象。但是,就像生成器一样,您只能对其迭代一次。因此,通过调用list(people2)
,您可以遍历filter
对象的每个元素以生成list
。至此,您已经到达了迭代过程的尽头,仅此而已。
因此,当您再次调用list(people2)
时,您将得到一个空列表。
演示:
>>> l = range(10)
>>> k = filter(lambda x: x > 5, l)
>>> list(k)
[6, 7, 8, 9]
>>> list(k)
[]
我应该提到,对于python2,
filter
返回一个列表,因此您不会遇到此问题。当您将py3的惰性评估带入图片时,就会出现问题。关于python - 过滤对象在迭代后变为空?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44420135/
10-16 03:15