首页 > 解决方案 > 如何解决 Python:IndexError:列表索引超出范围?

问题描述

我正在尝试计算“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

标签: pythonlist

解决方案


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

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


推荐阅读