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

为何enumerate()会导致后续zip()仅读取列表最后一项?

问题解析:循环变量覆盖原列表导致的异常输出

原代码

boylist = ['Jim', 'James', 'Jack', 'John', 'Jason']
for i, boylist in enumerate(boylist):
    print(f'Index {i} is {boylist} in my list')
#boylist = ['Jim', 'James', 'Jack', 'John', 'Jason']
girllist = ['Emma', 'Clara', 'Susan', 'Jill', 'Lisa']
for boylist, girllist in zip(boylist, girllist):
    print(f'{boylist} and {girllist} form a nice couple')

原输出

Index 0 is Jim in my list
Index 1 is James in my list
Index 2 is Jack in my list
Index 3 is John in my list
Index 4 is Jason in my list
J and Emma form a nice couple
a and Clara form a nice couple
s and Susan form a nice couple
o and Jill form a nice couple
n and Lisa form a nice couple

核心问题解答

1. 异常原因:变量名覆盖,和enumerate()本身无关

enumerate()不会修改原列表,问题出在第一个循环的变量命名:for i, boylist in enumerate(boylist)。

这里的boylist是循环迭代变量,每次循环会把原列表的元素(比如'Jim'、'James')赋值给这个变量。循环结束后,原本指向列表的boylist变量已经被覆盖成了最后一个迭代元素——字符串'Jason',不再是原来的列表对象。

第二个循环执行zip(boylist, girllist)时,boylist是字符串'Jason',而字符串是可迭代对象,会被拆成单个字符'J'、'a'、's'、'o'、'n',和girllist的元素一一配对,因此出现了奇怪的输出。

2. 不重新声明原列表的修复方法

只需要修改第一个循环的迭代变量名,避免覆盖原列表变量:

boylist = ['Jim', 'James', 'Jack', 'John', 'Jason']
# 将循环变量从boylist改为boy,避免覆盖原列表
for i, boy in enumerate(boylist):
    print(f'Index {i} is {boy} in my list')
girllist = ['Emma', 'Clara', 'Susan', 'Jill', 'Lisa']
# 同理,第二个循环也建议修改变量名,避免覆盖girllist
for boy, girl in zip(boylist, girllist):
    print(f'{boy} and {girl} form a nice couple')

修改后的正常输出:

Index 0 is Jim in my list
Index 1 is James in my list
Index 2 is Jack in my list
Index 3 is John in my list
Index 4 is Jason in my list
Jim and Emma form a nice couple
James and Clara form a nice couple
Jack and Susan form a nice couple
John and Jill form a nice couple
Jason and Lisa form a nice couple

日常写代码时,尽量避免用原容器的变量名作为迭代变量,养成清晰的命名习惯可以有效规避这类低级bug。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 20:20:24