You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jupyter Notebook中print语句异常求助:zip对象遍历问题解析

Python zip迭代器耗尽导致循环无输出的问题

问题场景

异常执行场景

执行以下代码时,for循环内的print语句完全没有输出:

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)]

正常执行场景1:注释第一个print

注释掉print(list(collect))后,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

正常执行场景2:打印迭代器对象而非转换为列表

将第一个print改为打印迭代器本身时,两个print都正常执行:

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

问题原因

  • Python中zip()返回的是迭代器对象,这类对象的核心特性是只能被遍历一次:遍历过程中会逐步消耗内部的元素,当所有元素都被取出后,迭代器就会变为空,无法再获取任何元素。
  • 在异常场景中,list(collect)会遍历整个迭代器,把所有元素转换为列表,这个操作直接耗尽了collect的所有元素。后续for循环遍历collect时,迭代器已经没有元素可以输出,所以循环内的print语句不会执行。
  • 而print(collect)只是打印迭代器的内存地址,并没有触发遍历操作,迭代器内的元素仍保留,因此后续for循环可以正常遍历输出。

解决方法

方法1:将迭代器转换为列表保存

如果需要先查看迭代器内容,同时后续还要继续使用元素,可提前将迭代器转换为列表存储,后续操作这个列表(列表是可重复遍历的容器):

z1=["a","b","c"]
z2=[1,2,3]
collect_list = list(zip(z1,z2))

print(collect_list)

for index,(item1,item2) in enumerate(collect_list):
    print(f"{index} corresponding to {item1} and {item2}")

方法2:重新生成迭代器

如果不需要保存所有元素,只是临时查看内容,可以在需要遍历的时候重新生成迭代器(前提是原序列z1、z2未被修改):

z1=["a","b","c"]
z2=[1,2,3]

print(list(zip(z1,z2)))

for index,(item1,item2) in enumerate(zip(z1,z2)):
    print(f"{index} corresponding to {item1} and {item2}")

内容的提问来源于stack exchange,提问作者jacob

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 16:53:10