【问题标题】:list value in while loop is always out of bounds [duplicate]while循环中的列表值总是超出范围[重复]
【发布时间】: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


【解决方案1】:

假设您坚持使用变量名称 list(您应该更改),您只能迭代到 list-1 的长度,因为您在循环内使用 x+1 对其进行寻址:

x = 0
while x < (len(list)-1):
    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)

【讨论】:

    【解决方案2】:

    x &lt; len(list) 之前,您无法运行此代码。必须是x &lt; len(list) - 1

    list = [(13,15),(-1,16),(12,17),(-5,-2),(2,5)]
    x = 0
    while x < len(list) -1 :
        print(x)
        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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多