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

Tuk*_*son 0 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)
Run Code Online (Sandbox Code Playgroud)

che*_*ner 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
Run Code Online (Sandbox Code Playgroud)

因此,尽管您对最初引用的列表有引用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'
Run Code Online (Sandbox Code Playgroud)