简体   繁体   English

For循环运行无限python

[英]For loop running infinite python

It's been 5 hours trying to find the issue but unable to identify why for loop for fn in L running infinite. 试图查找问题已经花费了5个小时,但无法确定for fn in L无限运行for fn in L原因for循环。

L=[]
N=int(raw_input())
for i in range(0,N):
    L.append(list(raw_input().split()))
print L

for fn in L:
    if 'insert'==fn[0]:
        L.insert(int(fn[1]),int(fn[2]))
    elif 'append'==fn[0]:
        L.append(int(fn[1]))
    elif 'remove'==fn[0]:
        L.remove(int(fn[1]))
    elif 'pop'==fn[0]:
        L.pop(int(fn[1]))
    elif 'index'==fn[0]:
        L.index(int(fn[1])) 
    elif 'count'==fn[0]:
        L.count(int(fn[1]))
    elif 'sort'==fn[0]:
        L.sort()     
    elif 'reverse'==fn[0]:
        L.reverse() 
    else :
        print  L

Inputs provided to list: 提供给列表的输入:

12
insert 0 5
insert 1 10
insert 0 6
print 
remove 6
append 9
append 1
sort 
print
pop
reverse
print

You're mutating your list in the loop. 您正在循环中更改列表。 Outcomes will be very unpredictable. 结果将是不可预测的。 You can instead iterate on a slice of the list: 您可以改为在列表的一部分上进行迭代:

for fn in L[:]:
    # your code here
    pass

In this way, the loop terminates when the items in the shallow copy (the slice) are exhausted. 这样,当浅表副本(切片)中的项目用尽时,循环终止。

You insert/remove elements while iterating the elements of a list. 您在迭代列表元素的同时插入/删除元素。 You also change the list by reversing the list. 您还可以通过反转列表来更改列表。 Both are mutation operations to the list which are not allowed during iteration. 两者都是对列表的变异操作,在迭代期间是不允许的。 The behavior is unspecified in this case. 在这种情况下,行为是不确定的。

for fn in L:
    if ...:
        L.insert(...)

You mutate the object used for looping ... and better you reverse it :p reverse <-- reverse --> reverse <-- reverse --> 您可以对用于循环的对象进行突变...最好将其反转:p reverse <-reverse-> reverse <-reverse->

:p :p

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

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