【问题标题】:I got error saying IndexError: list index out of range. how do I fix this?我收到错误提示 IndexError: list index out of range。我该如何解决?
【发布时间】:2020-11-09 07:24:05
【问题描述】:
   res = [3, 1, 1, 5, 2, 4, 2, 4, 2, 4, 3, 1, 1, 5, 3]      

   while not i>(len(res)-1):
        if res[i]==res[i+1]:
            answer+=2
            i+=2
        else:
            i+=1

变量“answer”应该计算彼此相邻的重复数字。出于某种原因,我收到错误消息 IndexError: list index out of range。我该如何解决这个问题?

【问题讨论】:

  • i == len(res) - 1 时会发生什么?满足条件not i > (len(res) - 1),然后执行if res[i] == res[i+1]。那么i + 1 是什么,res 是否应该在该索引处有一个元素?
  • 尝试推理:满足while 循环条件的i 的最大值是多少?如果您尝试在 if 条件中使用该值会发生什么 - 特别是,res[i+1] 是否有效?
  • 无论如何,如果输入数据连续有3个或更多相同的值会发生什么?

标签: python list index-error


【解决方案1】:

如果您还想计算重叠对,可以使用这种方法:

res = [3, 1, 1, 5, 2, 4, 2, 4, 2, 4, 3, 1, 1, 5, 3]
for i, j in zip(res, res[1:]):
    if i == j:
        amount += 2

另一种方法可能是:

for i, _ in enumerate(res):
    if i < len(res) - 1 and res[i] == res[i+1]:
        amount += 2

【讨论】:

    【解决方案2】:

    给它这种方法怎么样?

    res = [3, 1, 1, 5, 2, 4, 2, 4, 2, 4, 3, 1, 1, 5, 3]
    answer = 0
    start = 0
    while start < len(res):
        if start + 1 < len(res):
            if res[start] == res[start + 1]:
                answer += 1
                start += 2
            else:
                start += 1
        else:
            start += 1
    print(answer)
    

    【讨论】:

    • 这只会计算重复项,但如果输入数据连续有3个或更多相同的值,将使用不同的方法。
    【解决方案3】:

    让我们从稍微简化一下代码开始。条件

    not i > (len(res) - 1)
    

    可以转换成

    i <= (len(res) - 1)
    

    可以进一步转化为

    i < len(res)
    

    这意味着i 将始终小于res 的长度,这使其成为有效索引。但是,在while 的正文中,这一行:

    if res[i]==res[i+1]:
        ...
    

    我们使用i + 1res 编制索引,对于i 的最后一个可能值将是无效索引(i + 1 将等于len(res))。我们必须确保不仅i 小于len(res),而且 i + 1 小于len(res),给我们这个固定版本的代码:

    while i + 1 < len(res):
        if res[i] == res[i + 1]:
            answer += 2
            i += 2
        else:
            i += 1
    

    在您的示例 res 上运行此代码给出的 answer 为 4,看起来正确。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-10-09
      • 2020-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-14
      • 2021-02-28
      • 1970-01-01
      相关资源
      最近更新 更多