【发布时间】:2019-09-09 17:30:49
【问题描述】:
我正在尝试将列表中的重叠间隔组合在一起,以创建一个较小的列表,其中只有不重叠的间隔。但是,我不断收到 IndexError: list index out of range on my if 语句。
我尝试过使用 for 循环,但这似乎是一个倒退,因为 for 循环语句中列表的长度是静态的。
list = [(13,15),(-1,16),(12,17),(-5,-2),(2,5)]
x = 0
while x < len(list):
if list[x][0] < list[x+1][0] and list[x][1] > list[x+1][1]:
del list[x+1]
if list[x][0] > list[x+1][0] and list[x][1] > list[x+1][1]:
tuple2 = (list[x+1][0], list[x][1])
list.append(tuple2)
del list[x]
del list[x+1]
if list[x][0] < list[x+1][0] and list[x][1] < list[x+1][1]:
tuple2 = (list[x][0], list[x+1][1])
list.append(tuple2)
del list[x]
del list[x+1]
x = x + 1
print(list)
预期输出为:[(-5,-2),(-1,17)]
【问题讨论】:
-
你能提供你的整个代码吗?我有点困惑,因为
list是 Python 中的一个函数,我不确定你的变量x是什么。 -
1) 不要使用
list作为变量名,它会遮蔽内置的list类型并且会导致奇怪的错误。 2) 你在这段代码中有很多x+1s,但是x被允许上升到len(list) - 1;换句话说,您尝试访问的最大索引是len(list) - 1 + 1,它总是超出范围。 3) 迭代列表时向列表中添加项目或从列表中删除项目是灾难的根源。通常解决方案是对列表的副本进行操作。 -
List 是我的列表的名字,但是我只是把变量名改成了list1。如果 x +1 导致列表超出范围,我如何在迭代时调用列表中的下一个元素?
-
当 x == len(list) -1 of curse using x + 1 将导致错误你在最后一个元素都准备好了。
-
只是好奇。如果删除索引
x,列表的内容不会上移吗?那么在x之后删除x+1对吗?
标签: python while-loop index-error