简体   繁体   English

在迭代时附加到列表是否正确?

[英]Is it correct to append to a list while iterating over it?

I see that I can append to a list while iterating over it 我看到我可以在迭代它时附加到列表中

lst = [1]
for i in lst:
    lst.append(i+1)
    print(i)

Am I allowed to make use of this behavior? 我可以利用这种行为吗? or is it discouraged? 还是气馁? I note that the same can not be said for set 我注意到同样不能说set

lst = set([1])
for i in lst:
    lst.add(i+1)
    print(i)

Error: size changed during iteration. 错误:迭代期间大小已更改。

Appending to a list while iterating over it is allowed because lists are ordered so the behavior of appending during iteration is predictable. 允许在迭代时附加到列表,因为列表是有序的,因此在迭代期间追加的行为是可预测的。 This makes it useful for retrying failing tasks when all the other tasks in the queue have finished, for example: 这使得在队列中的所有其他任务完成时重试失败任务非常有用,例如:

tasks = ['task1', 'task2']
for task in tasks:
    if task == 'task1':
        tasks.append('task1-retry')
    print(task)

This outputs: 这输出:

task1
task2
task1-retry

But sets are not ordered, so adding an item to a set while iterating over it sequentially has an indeterminate effect, and is therefore disallowed. 但是集合没有排序,因此在按顺序迭代集合时向集合添加项目具有不确定的效果,因此不允许。

I think it will not work because, if list size changed then(?) loop items should change as well, eg it will probably become infinite loop or memory access violation. 我认为它不会起作用,因为如果列表大小发生变化,那么(?)循环项也应该改变,例如它可能会变成无限循环或内存访问冲突。 Better do it that way: 最好这样做:

list=[1,2,7,5]
list2=[]
for i in list:
  list2.append(i+1)
  print(i)
list=list+list2

As others have already said you will create and infinite loop. 正如其他人已经说过你将创造和无限循环。 But you can catch that with the break statement in python: https://docs.python.org/2.0/ref/break.html 但你可以用python中的break语句来捕获它: https//docs.python.org/2.0/ref/break.html

But then again if you catch it with a break you could rewrite it into another loop where it stops whenever the condition is fulfilled that you use for the break statement. 但是如果你再次捕获它,你可以将它重写为另一个循环,只要满足你用于break语句的条件,它就会停止。

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

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