简体   繁体   English

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

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

In my case I have a for loop, looping through a list, but I want to change that list in said loop. 就我而言,我有一个for循环,遍历一个列表,但是我想在上述循环中更改该列表。 After that I want the for loop to iterate through the new list. 之后,我希望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] 

How can I do something like that? 我该怎么做?

Allthough @BoarGules's comment is correct, you may solve your problem using enumerate. 尽管@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]

This outputs: 输出:

>4
>5
>9
>9
>9

You shouldn't change the list through iteration. 您不应该通过迭代来更改列表。 I would use indexing: 我会使用索引:

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

To see why this doesn't work, a for loop is equivalent to a while loop like this: 要了解为什么这行不通, for循环等效于while循环,如下所示:

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

If you assign something new to y , the loop isn't affected, because it only uses the iterator over the original value assigned to y , not the name y itself. 如果为y分配新的内容,则该循环不会受到影响,因为它仅在分配给y的原始值(而不是名称y本身)上使用迭代器。

However, if you do mutate the list in the body of the loop, the iterator might return a value you don't expect. 但是,如果您确实在循环体内更改了列表,则迭代器可能会返回您不期望的值。 If you need to change the iterable, it's best to get the iterator yourself. 如果需要更改迭代器,最好自己获取迭代器。

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