【问题标题】:How to resolve Python: IndexError: list index out of range?如何解决 Python:IndexError:列表索引超出范围?
【发布时间】:2021-10-01 17:30:16
【问题描述】:

我正在尝试计算“args”列表中“-1”的出现次数。 '-1' 出现在很多地方,所以当它连续出现不止一次时,我希望计算一下。

我收到“列表索引超出范围”错误,但这是错误的。我正在尝试访问第 16 个元素,“args”的长度为 19。在第 5 行和第 6 行,我分别打印索引和列表的元素,这些行执行没有错误。

为什么我会收到错误消息?而且第10行的print语句没有打印,是什么原因?

args=[-3, -1, -1, -1, -1, -2, -1, -1, -2, -1, -1, -1, -1, -3, -1, -2, -1, -1, -1]
i=0
while  i<= len(args)-1:
    count=0
    print(i)
    print(args[i])
    while args[i]==-1:
        count+=1
        i+=1 
    print("count="+str(count)+"-"+str(i))
    i+=1


$python main.py
0
-3
count=0-0
1
-1
count=4-5
6
-1
count=2-8
9
-1
count=4-13
14
-1
count=1-15
16
-1
Traceback (most recent call last):
  File "main.py", line 8, in <module>
    while args[i]==-1:
IndexError: list index out of range

【问题讨论】:

  • 错误不是发生在外循环,而是发生在内循环。您的最后一个元素是-1,因此它会再次执行并导致错误。因为,它不需要-1会导致错误,错误发生在检查之前
  • 也检查内部 for 循环中的越界条件
  • 预期输出是什么?
  • 我强烈建议不要使用 while 而不是 if 子句(我假设您尝试过)。我也推荐Python的for (each) loop

标签: python list


【解决方案1】:

这里的主要问题发生在您执行while args[i] == -1 时。

出现问题的原因是,如果您的最后一个值为-1,您将增加索引,然后您将尝试在不存在的索引中访问args

@Karin here 回答了您的一般问题(计算连续值)有一个更快的解决方案:

from itertools import groupby
list1 = [-1, -1, 1, 1, 1, -1, 1]
count_dups = [sum(1 for _ in group) for _, group in groupby(list1)]
print(count_dups)

【讨论】:

    【解决方案2】:

    IndexError 是因为您的内部 while 循环。您正在递增 i 而不检查它是否超过列表长度并尝试访问它。

    还有另一种方法可以解决这个问题。

    您可以跟踪以前访问的元素,检查它是否为 -1 并检查以前和当前元素是否相同,然后才增加计数器 count

    args=[-3, -1, -1, -1, -1, -2, -1, -1, -2, -1, -1, -1, -1, -3, -1, -2, -1, -1, -1]
    
    prev = args[0]
    count = 0 
    i = 1
    while  i < len(args):
        if args[i] == -1 and args[i] == prev:
            count += 1
        else:
            if count > 1:
                print(count)
            count = 1
        prev = args[i]
        if i == len(args) - 1 and count > 1:
            print(count)
        i+=1
    

    这将打印列表中连续出现的-1s 的计数。

    【讨论】:

    • 非常感谢
    猜你喜欢
    • 2012-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多