迭代后过滤器对象变空? [英] filter object becomes empty after iteration?
问题描述
我正在学习如何使用 filter
函数.
这是我写的代码:
people = [{'name': 'Mary', 'height': 160},{'name': 'Isla', 'height': 80},{'姓名':'山姆'}]people2 = filter(lambda x: x 中的高度",人)
如您所见,我正在尝试删除所有不包含 'height'
键的字典.
代码工作正常,事实上如果我这样做:
print(list(people2))
我明白了:
[{'name': 'Mary', 'height': 160}, {'name': 'Isla', 'height': 80}]
问题是如果我做两次:
print(list(people2))打印(列表(人 2))
第二次,我得到一个空列表.
你能解释一下为什么吗?
这是一个经典的python3 doh!
过滤器是一种特殊的可迭代对象,您可以对其进行迭代.然而,就像一个生成器,你只能迭代它一次.因此,通过调用 list(people2)
,您将迭代 filter
对象的每个元素以生成 list
.在这一点上,您已经到达了可迭代对象的末尾,没有什么可以返回了.
因此,当您再次调用 list(people2)
时,您会得到一个空列表.
演示:
<预><代码>>>>l = 范围(10)>>>k = 过滤器(λ x: x > 5, l)>>>列表(k)[6, 7, 8, 9]>>>列表(k)[]我应该提到,对于 python2,filter
返回一个列表,所以你不会遇到这个问题.当你把py3的惰性求值带入画面时,问题就出现了.
I'm learning how to use the filter
function.
This is the code I've written:
people = [{'name': 'Mary', 'height': 160},
{'name': 'Isla', 'height': 80},
{'name': 'Sam'}]
people2 = filter(lambda x: "height" in x, people)
As you can see what I'm trying to do is to remove all the dictionaries that don't contain the 'height'
key.
The code works properly, in fact if I do:
print(list(people2))
I get:
[{'name': 'Mary', 'height': 160}, {'name': 'Isla', 'height': 80}]
The problem is that if I do it twice:
print(list(people2))
print(list(people2))
the second time, I get an empty list.
Can you explain me why?
This is a classic python3 doh!.
A filter is a special iterable object you can iterate over. However, much like a generator, you can iterate over it only once. So, by calling list(people2)
, you are iterating over each element of the filter
object to generate the list
. At this point, you've reached the end of the iterable and nothing more to return.
So, when you call list(people2)
again, you get an empty list.
Demo:
>>> l = range(10)
>>> k = filter(lambda x: x > 5, l)
>>> list(k)
[6, 7, 8, 9]
>>> list(k)
[]
I should mention that with python2, filter
returns a list, so you don't run into this issue. The problem arises when you bring py3's lazy evaluation into the picture.
这篇关于迭代后过滤器对象变空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!