首页 > 解决方案 > 为什么在两次调用 zip 上的列表时返回空列表

问题描述

如下python代码所示,为什么在调用第二个时会打印空列表list(ll)

l1 = [1,2,3]
l2 = [4,5,6]
ll = zip(l1,l2,l1,l2)
ll
<zip at 0x23d50b10f40>
list(ll)
[(1, 4, 1, 4), (2, 5, 2, 5), (3, 6, 3, 6)]
ll
<zip at 0x23d50b10f40>
list(ll)
[]

标签: pythonlist

解决方案


因为zip是一个 Iterator 对象。当您list(ll)第一次调用时,zip对象中的值会被消耗掉。这就是为什么当您list再次调用时,没有其他可显示的内容。

zip是一个函数,当应用于可迭代对象时,会返回一个迭代器。意思是,除非它被迭代,否则它不会计算任何值。

例如:

>>> z = zip([1, 2, 3], [3, 4, 5])
>>> z
<zip at 0x1e46824bec0>

>>> next(z)    # One value is computed, thus consumed, now if you call list:
(1, 3)

>>> list(z)    # There were only two left, and now even those two are consumed
[(2, 4), (3, 5)]

>>> list(z)    # Returns empty list because there is nothing to consume
[]

推荐阅读