为什么此打印会更改以下结果?

Why this print changing the following result?

示例代码:

p = map(some_logic)
print(list(p)) # HERE
p = filter(some_logic, p)
print(list(p))

使用上面的代码,第一行生成的p总是一样的。但是通过添加注释行 HERE,最后打印输出 []。如果没有 HERE 行,最后的 print 给出 p.

的正确内容

这是什么原因造成的?

当您使用 map 调用的结果时,它会被消耗:

>>> p = map(int, ['1', '2'])
>>> p
<map object at 0x02C878B0>
>>> list(p)
[1, 2]
>>> list(p)
[]

您应该存储将 map 更改为 list 的结果:

>>> p = list(map(int, ['1', '2']))
>>> p
[1, 2]
>>> p = list(filter(lambda x: x == 1, p))
>>> p
[1]

请注意,filter 也会发生同样的事情,因此我也将其更改为 list