[英]How to resolve Python: IndexError: list index out of range?
我正在嘗試計算列表“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
在您的內部while
循環中,您需要檢查它以防止i
超出 args 范圍
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 i <= len(args)-1 and args[i]==-1: # here to modify your code
count+=1
i+=1
print("count="+str(count)+"-"+str(i))
i+=1
這里的主要問題發生在while args[i] == -1
。
有問題的原因是,如果您的最后一個值是-1
,您將增加索引,然后您將嘗試訪問不存在的索引中的args
。
對於您的一般問題(計算連續值),有一個更快的解決方案,正如@Karin在這里回答的那樣:
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)
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
的計數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.