del C [0]直到带有while循环的len(C)== 1

时间:2020-04-18 05:17:45

标签: python loops for-loop while-loop

基本上,我想删除列表左侧的每个元素,直到剩下一个元素为止。然后休息。我也遍历了c的每个索引,因为它是子列表的列表。我正在删除内部列表中的第一个元素。 (例如,list == 1234...。1234、234、34,最后是4)

编辑:最近我的电脑很奇怪。如果while循环在计算机上不是无限的。请考虑我可能会或可能导致无限循环的任何错误。我不知道这是怎么回事。

r=[];
c = [[1,2],[3,2],[3],[1]]
for j in range(1, len(c)):
    if str(any(elem in c[0] for elem in c[j])) == 'False':
        r.append(c[j])
if j == len(c) - 1:
    del c[0]
    r[:] = []
    print(r, c)

输出

[] [[3, 2], [3], [1]]

详细结果

# The statement has succesfully deleted c[0]
# >>> c
#[[3, 2], [3], [1]]

#The statement has succesfully cleared the list
# >>> r
#[]


# Basically, I want to delete each element to the left of the list until there is one element left. And then break. 

# (eg. 1234, 234, 34, and finally 5)
# There are 10 steps in this loop. because 1+2+3+4 == 10

现在打算执行上述语句的循环现在陷入了无限循环。

c = [[1,3],[3,2],[3,4],[1]]
r=[];
while len(c) > 1:
    for j in range(1, len(c)):
        if str(any(elem in c[0] for elem in c[j])) == 'False':
            r.append(c[j])
            r.append(c[0])
            # we use print(r) to show bug
            print(r)
        if j == len(c) - 1:
            # This statement is intended to break an infinite loop but fails to do so.
            del c[0]
            r[:] = []
            if len(c) == 1:
                quit()



print(r)

输出

[3,4],[1],[2,3],[1,3],[1,3]... infinite loop output

输出不是问题。无需详细介绍输出。我只需要弄清楚如何遍历上面举例说明的元素列表。

问题

在while循环中导致无限循环的错误是什么? 您可以给我任何解决方案,以便我学会不再犯同样的错误吗?

1 个答案:

答案 0 :(得分:1)

可以吗?

c = [[1,3], [3,2], [3,4], [1]]
r = []

while len(c) - 1:
    r.append(c.pop(0))

print("r", r, "\nc", c)

# results:
# r [[1, 3], [3, 2], [3, 4]] 
# c [[1]]