我在 Jupyter Notebook 中使用 Python 中的
zip
函数,当时我注意到打印语句没有打印。这是单元格中包含的代码:
z1=["a","b","c"]
z2=[1,2,3]
collect=zip(z1,z2)
print(list(collect))
for index,(item1,item2) in enumerate(collect):
print(f"{index} corresponding to {item1} and {item2}")
这段代码输出
[('a', 1), ('b', 2), ('c', 3)]
Jupyter 完全忽略 for 循环中的 print 语句!
但是,我注意到,如果我注释掉第一个打印语句,则 for 循环中的打印语句就会打印。所以,如果单元格中的代码是
z1=["a","b","c"]
z2=[1,2,3]
collect=zip(z1,z2)
#print(list(collect))
for index,(item1,item2) in enumerate(collect):
print(f"{index} corresponding to {item1} and {item2}")
然后输出变成
0 corresponding to a and 1
1 corresponding to b and 2
2 corresponding to c and 3
还有一点非常奇特,那就是如果我将单元格中的打印语句更改为其他内容,例如
print(collect)
,则两个打印语句都会打印。 IE。如果我将代码更改为
z1=["a","b","c"]
z2=[1,2,3]
collect=zip(z1,z2)
print(collect)
for index,(item1,item2) in enumerate(collect):
print(f"{index} corresponding to {item1} and {item2}")
输出变成
<zip object at 0x7fadf85db0c0>
0 corresponding to a and 1
1 corresponding to b and 2
2 corresponding to c and 3
这太奇怪了!!!我只是想知道是否有人知道为什么会发生这种情况,或者如何解决它?老实说,我在 Jupyter Notebook 中打印时遇到了一些问题。谢谢你。
实际上,这与 Jupyter Notebook 无关,而是与
zip
返回的内容有关。
zip
返回一个迭代器对象。一旦耗尽它(例如,通过从其所有元素创建一个列表),它就是空的,迭代它相当于迭代空集合。
这就是为什么打印
list(collect)
会阻止它工作,而其他任何东西都可以正常工作。
通过重复打印语句,您可以轻松看到这一点:
z1=["a","b","c"]
z2=[1,2,3]
collect=zip(z1,z2)
print(list(collect)) # [('a', 1), ('b', 2), ('c', 3)]
print(list(collect)) # []