首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >这里发生什么事情?使用for people in people print people循环

这里发生什么事情?使用for people in people print people循环
EN

Stack Overflow用户
提问于 2018-05-19 01:23:20
回答 1查看 40关注 0票数 0
代码语言:javascript
复制
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)
EN

回答 1

Stack Overflow用户

发布于 2018-05-19 01:25:19

for循环不会为索引创建新的作用域;您将使用循环索引people覆盖列表people

for循环几乎是以下代码的语法糖:

代码语言:javascript
复制
# 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]),您可以看到相同的事情:

代码语言:javascript
复制
>>> people[-1]
'mat'
>>> people[-1][-1]
't'
>>> people[-1][-1][-1]
't'
>>> people[-1][-1][-1][-1]
't'
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50416452

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档