people = ['mago','pipa','john','mat']
>>> for people in people:
print(people)
mago
pipa
john
mat
>>> for people in people:
print(people)
m
a
t
>>> for people in people:
print(people)
t
>>> for people in people:
print(people)
t
>>> for people in people:
print(people)
t
>>> for people in people:
print(people)
for
循环不会为索引创建新的作用域;您正在用循环索引people
覆盖列表people
for
循环几乎是以下代码的语法糖分:因此,尽管您有一个对最初由
people
引用的列表的引用,名称people
会不断更新,以引用该列表中的一个元素。运行第二个循环时,people
现在是对列表中最后一个字符串的引用。第三个和随后的循环表示一个固定点;对字符串的迭代器返回连续的1个字符的字符串,因此您很快就会到达一个点,其中字符串是它自己的唯一元素在您的示例中,
people
在第一个循环之后绑定到"mat"
,而不是您的列表。在第二个(以及第三个和第四个)循环之后,people
被绑定到"t"
通过将调用链接到
__getitem__
(即[-1]
),可以看到相同的情况:相关问题 更多 >
编程相关推荐