繁体   English   中英

在该循环中迭代的变更列表

[英]Change list, that you are iterating through, in that loop

就我而言,我有一个for循环,遍历一个列表,但是我想在上述循环中更改该列表。 之后,我希望for循环遍历新列表。

li = [4,5,6,7,8,9]
for item in li:
    #do something

    if item == 5:
        #now continue iterating through this loop and not the old one
        li = [9,9,9,9,9,9] 

我该怎么做?

尽管@BoarGules的评论是正确的,但您可以使用枚举解决问题。

li = [4,5,6,7,8,9]
for i, item in enumerate(li):
    print(li[i])
    if li[i] == 5:
        li = [9,9,9,9,9,9]

输出:

>4
>5
>9
>9
>9

您不应该通过迭代来更改列表。 我会使用索引:

for i in range(len(li)):
    if li[i] == 5:
        li = len(li) * [9]

要了解为什么这行不通, for循环等效于while循环,如下所示:

# for x in y:
#    ...
itr = iter(y)
while True:
    try:
        x = next(itr)
    except StopIteration:
        break
    ...

如果为y分配新的内容,则该循环不会受到影响,因为它仅在分配给y的原始值(而不是名称y本身)上使用迭代器。

但是,如果您确实在循环体内更改了列表,则迭代器可能会返回您不期望的值。 如果需要更改迭代器,最好自己获取迭代器。

li = [4,5,6,7,8,9]
itr = iter(li)
while True:
    try:
        item = next(itr)
    except StopIteration:
        break
    #do something

    if item == 5:
        #now continue iterating through this loop and not the old one
        itr = iter([9,9,9,9,9])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM