Python del C[0]直到len(C)==1并带有while循环
基本上,我想删除列表左侧的每个元素,直到剩下一个元素。然后休息。我还循环遍历c的每个索引,因为它是一个子列表列表。我正在删除内部列表中的第一个元素。(例如列表==1234…1234,234,34,最后4) 编辑:我的电脑最近很奇怪。如果while循环在计算机上不是无限的。请考虑我可能或可能导致无限循环的任何错误。我不知道发生了什么事Python del C[0]直到len(C)==1并带有while循环,python,loops,for-loop,while-loop,Python,Loops,For Loop,While Loop,基本上,我想删除列表左侧的每个元素,直到剩下一个元素。然后休息。我还循环遍历c的每个索引,因为它是一个子列表列表。我正在删除内部列表中的第一个元素。(例如列表==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
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
用于执行上述语句的While循环现在被卡在无限for循环中
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循环中有哪些错误使它成为一个无限循环?
你能给我什么解决办法,让我学会不再犯同样的错误吗?就是这样吗
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]]
请注意,将布尔值转换为字符串来测试它是非常低效的<代码>如果str(any(elem in c[0]表示elem in c[j]))='False':应该写得更简单
如果没有任何(elem in c[0]表示elem in c[j]):
或者与集合相交:如果没有设置(c[0])&set(c[j]):
您正在字符串、列表和嵌套列表之间切换。一、 同样,你也很难理解为什么要经历这个复杂的过程。这应该可以。我将实现其他if语句以输出所需的输出。