>>> a = filter(lambda x: x&1, [1,2])
>>> list(a)
[2]
>>> list(a)
[]
这很反常,不是吗?所以,如果谁能解释一下为什么会这样,请随意!
对了,我使用的是Python 3.8.2。
既然你知道要把调用的结果包装到 filter
与 list()
我假设你熟悉发电机函数及其同类的概念。在这里,我想说的是 filter
函数返回的东西实际上类似于一个生成函数,因为它只能被迭代一次。见下文。
>>> a = filter(lambda x: x^1, [1,2])
>>> type(a)
<class 'filter'>
>>> it = iter(a)
>>> next(it)
2
>>> next(it)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>> it = iter(a) # try to iterate the filter a second time
>>> next(it) # you will get a StopIteration exception the very first time
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>>
上面的代码本质上等同于:
a = filter(lambda x: x^1, [1,2])
print(type(a))
for item in a:
print(item)
for item in a:
print(item)
a是一个可迭代的对象, 当你第一次调用list(a)时, 它的项目已经被消耗掉了. 随后的list(a)将一无所获。
同理。
a = (i for i in range(10))
list(a)
[0, 1....10]
list(a)
[]
我更喜欢C#的行为,它有不同的IEnumerable和IEnumerator接口。