Python - 为什么 enumerate() 导致稍后的 zip() 仅从列表中的最后一项提取?

Fak*_*son 2 python string list enumerate python-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')\
Run Code Online (Sandbox Code Playgroud)

输出:

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
Run Code Online (Sandbox Code Playgroud)

当我取消注释时,第 4 行输出是正确的,并且会打印每个全名。所以我的问题是为什么会发生这种情况?enumerate 对我的列表做了什么操作导致了这种行为?我该如何解决这个问题而不重新声明我的原始列表?

我尝试过尝试并打印出枚举列表和压缩列表的输出,但我不明白是什么原因导致的。希望看到列表索引地址可能停留在最终值,但我无法找到任何内容或重置该地址。

Bar*_*mar 7

因为您boylist在第一个循环中用作迭代变量for。因此,每次迭代都会设置boylist为原始列表的元素之一。在循环的末尾,boylist包含最后一个男孩的名字。因此,第二个循环是迭代 的字符Jason,而不是原始 中的名称boylist

不要重用这样的变量,使用

boylist = ['Jim', 'James', 'Jack', 'John', 'Jason']
for i, boy in enumerate(boylist):
    print(f'Index {i} is {boy} in my list')

girllist = ['Emma', 'Clara', 'Susan', 'Jill', 'Lisa']
for boy, girl in zip(boylist, girllist):
    print(f'{boy} and {girl} form a nice couple')
Run Code Online (Sandbox Code Playgroud)