加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 为什么zip对象消失了?

发布时间:2020-12-20 11:34:18 所属栏目:Python 来源:网络整理
导读:请查看代码,为什么列表(w)正确显示,h什么都不显示? x=[1,2,3] y=[4,5,6] w=zip(x,y) list(w)[(1,4),(2,5),(3,6)] h=list(w) h[] 解决方法 在Python 3中, zip 返回 iterator1. Make an iterator that aggregates elements from each of the iterables. 迭代
请查看代码,为什么列表(w)正确显示,h什么都不显示?

>>> x=[1,2,3]
>>> y=[4,5,6]
>>> w=zip(x,y)
>>> list(w)
[(1,4),(2,5),(3,6)]
>>> h=list(w)
>>> h
[]

解决方法

在Python 3中,zip返回 iterator1.

Make an iterator that aggregates elements from each of the iterables.

迭代器会记住迭代的位置;在h = list(w)行,迭代器已经“在结尾”,因此导致空列表/序列.

尝试使用w = list(zip(x,y)),这将强制迭代器到列表一次.

1 Python 2中的zip返回一个列表,因此这种行为仅在Python 3中展示.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读