我想学习zip类的功能。我写了一个非常简单的例子。在
>>> names = ['name1','name2','name3']
>>> ages = ['age1','age2','age3']
>>> print(zip(names, ages))
<zip object at 0x03DB18F0>
>>> zipped = zip(names, ages)
for i in zipped:
type(i)
print(i)
结果是(正如预期的那样)—
^{pr2}$但是如果我在这一行后面写下:
for i in zipped:
print(i)
它编译但不打印任何内容!在
我又检查了一遍-
>>> zipped = zip(names, ages)
>>> for i in zipped:
print(i)
('name1', 'age1')
('name2', 'age2')
('name3', 'age3')
这次打印正确。但是在解压的时候-
>>> names2, ages2 = zip(*zipped)
Traceback (most recent call last):
File "<pyshell#29>", line 1, in <module>
names2, ages2 = zip(*zipped)
ValueError: not enough values to unpack (expected 2, got 0)
由于某种原因,zipped
变量似乎变空了?在
Note: if required you may change the title of the question. I am using python 3.6.1 on a windows (10) machine.
{{cd2>返回一个
您可以使用
list(zip(names, ages))
从迭代器中创建一个列表。在list
使用iterator对象创建一个列表,该列表可以重复多次。在您可以在这里阅读有关zip函数的更多信息。在
zip
生成一个只能迭代一次的迭代器(<zip object at 0x03DB18F0>
)。一旦你迭代了它,它就耗尽了。如果您想生成一个列表,该列表可以根据您的需要进行多次迭代:相关问题 更多 >
编程相关推荐