python - 为什么在两次调用 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)
[]
解决方案
因为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
[]
推荐阅读
- javascript - 如何从 JavaScript 中的 API 更新页面以进行下一次搜索?
- angular - 如何在与 y 轴平行的直线下方直接显示 Angular 中剑道图表的 x 轴标签?
- ruby-on-rails - 成功验证用户名和密码后,doorkeeper gem 给出“invalid_client”
- regex - Logstash grok 模式提取字符串的一部分以开头和结尾
- php - 向 WooCommerce 单品页面添加多个元字段
- reactjs - 错误 LessError:找不到模块'@/utils/utils.less'
- reactjs - 如何在特定屏幕上隐藏顶部标签栏?
- javascript - 如何在数据层中正确悬停圆圈
- r - 如何对超过 2 个数据块进行 PLS(混合组学)?
- c# - 关于 c# 和 unity 中的实例方法