这里发生了什么?与人们在人们打印人循环

时间:2018-05-18 17:23:20

标签: python for-loop

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)

1 个答案:

答案 0 :(得分:5)

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现在是对列表中 last 字符串的引用。第三个和后续循环代表一个固定点;字符串上的迭代器返回连续的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'