zip variable empty after first use(首次使用后 zip 变量为空)
问题描述
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 对象存在于 0xa8d48ec>.我什至可以重新分配 t、t2 以再次压缩,但它只能工作一次,而且只能工作一次.
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 中,许多内置函数现在返回迭代器而不是列表(map、zip、filter)
Note that in python3.x, a lot of the builtin functions now return iterators rather than lists (map, zip, filter)
这篇关于首次使用后 zip 变量为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:首次使用后 zip 变量为空
基础教程推荐
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
