这是怎么回事?在人物打印人物循环中使用for people

2024-06-16 15:07:23 发布

您现在位置:Python中文网/ 问答频道 /正文

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)

Tags: inforjohnpeopleprintmatmagopipa
1条回答
网友
1楼 · 发布于 2024-06-16 15:07:23

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'

相关问题 更多 >