首次使用后zip变量为空 [英] zip variable empty after first use

查看:69
本文介绍了首次使用后zip变量为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python 3.2

Python 3.2

t = (1, 2, 3)
t2 = (5, 6, 7)
z = zip(t, t2)

for x in z:
    print(x)

结果:

(1, 5)
(2, 6)
(3, 7)

紧接着在完全相同的循环中放入任何内容,

Putting in EXACTLY the same loop immediately after, nothing is printed:

for x in z:
    print(x)

z仍以<zip object at 0xa8d48ec>的形式存在.我什至可以重新分配tt2使其再次压缩,但随后它只能工作一次,并且只能再次工作.

z still exists as <zip object at 0xa8d48ec>. I can even reassign the t, t2 to be zipped again, but then it only works once and only once, again.

这是应该如何工作的吗?在文档中没有提及.

Is this how its supposed to work? There's no mention in the docs about this.

推荐答案

这就是它在python 3.x中的工作方式.在python2.x中,zip返回一个元组列表,但是对于python3.x,zip的行为类似于itertools.izip在python2.x中的行为.要恢复python2.x的行为,只需从zip的输出构造一个列表:

That's how it works in python 3.x. In python2.x, zip returned a list of tuples, but for python3.x, zip behaves like itertools.izip behaved in python2.x. To regain the python2.x behavior, just construct a list from zip's output:

z = list(zip(t,t2))

请注意,在python3.x中,许多内置函数现在返回迭代器,而不是列表(mapzipfilter)

Note that in python3.x, a lot of the builtin functions now return iterators rather than lists (map, zip, filter)

这篇关于首次使用后zip变量为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆