【问题标题】:del C[0] until the len(C) == 1 with a while loopdel C[0] 直到 len(C) == 1 和 while 循环
【发布时间】:2020-07-31 17:12:57
【问题描述】:

基本上,我想删除列表左侧的每个元素,直到剩下一个元素。然后打破。我还循环遍历 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

虽然用于执行上述语句的循环现在陷入了无限 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 循环中有哪些错误导致它成为无限循环? 你有什么解决办法可以让我学会不再犯同样的错误吗?

【问题讨论】:

  • 请注意,将布尔值转换为字符串来测试它是非常低效的; if str(any(elem in c[0] for elem in c[j])) == 'False': 应该写得更简单if not any(elem in c[0] for elem in c[j]): 或设置交集:if not set(c[0]) & set(c[j]):
  • 您正在字符串、列表和嵌套列表之间切换。我也很难理解你为什么要经历这个复杂的过程。

标签: python loops for-loop while-loop


【解决方案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]]

【讨论】:

  • 这应该可以。我将执行我的其他 if 语句来输出我想要的输出。
猜你喜欢
  • 2020-09-29
  • 1970-01-01
  • 2012-10-10
  • 2011-10-21
  • 2013-07-12
  • 1970-01-01
  • 2014-04-12
  • 2019-02-15
  • 2015-06-29
相关资源
最近更新 更多