简体   繁体   English

枚举列表中的 Python for 循环无限

[英]Python for loop in enumerate list goes for infinite

I have a list of numbers and I want to run a for-loop through it, but as I update the list, the for loop does not stop and runs infinite time, here is my code:我有一个数字列表,我想通过它运行一个 for 循环,但是当我更新列表时,for 循环不会停止并无限运行,这是我的代码:

a = [0,1,2,3,4,5,6]
for index, item in enumerate(a):
   if item>0:
       a.insert(index,10)

What should I do to just update and insert into list "a" and just doing for loop for pre defined list before adding new items?在添加新项目之前,我应该怎么做才能更新并插入列表“a”并为预定义列表执行 for 循环?

Is that what you are looking for?这就是你要找的吗? (it is not clear..) (不清楚..)
The code replaces every positive value with 10代码用 10 替换每个正值

a = [0, 1, 2, 3, 4, 5, 6]
a1 = [10 if x > 0 else x for x in a]
print(a1)

output输出

[0, 10, 10, 10, 10, 10, 10]

您可以遍历此列表的副本:

for index, item in enumerate(a.copy()):

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

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