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)发布于 2018-05-19 01:25:19
for循环不会为索引创建新的作用域;您将使用循环索引people覆盖列表people。
for循环几乎是以下代码的语法糖:
# for people in people: # iter() is called implicitly on the iterable
# print(people)
people_itr = iter(people)
while True:
try:
people = next(people_itr)
except StopIteration:
break
print(people)
del people_itr因此,尽管您拥有对最初由people引用的列表的引用,但是名称people会不断更新以引用该列表中的一个元素。当您运行第二个循环时,people现在是对列表中最后一个字符串的引用。第三个和随后的循环表示一个固定点;字符串上的迭代器返回连续的1个字符的字符串,因此您很快就会到达字符串是它自己的唯一元素的点。
在您的示例中,在第一个循环之后,people被绑定到"mat",而不是您的列表。在第二次(第三次和第四次)循环之后,people绑定到"t"。
通过将调用链接到__getitem__ (即,[-1]),您可以看到相同的事情:
>>> people[-1]
'mat'
>>> people[-1][-1]
't'
>>> people[-1][-1][-1]
't'
>>> people[-1][-1][-1][-1]
't'https://stackoverflow.com/questions/50416452
复制相似问题