我正在尝试计算'args‘列表中'-1’的出现次数。'-1‘出现在许多地方,所以当它连续出现不止一次时,我希望对其进行计数。
我得到了一个“列表索引超出范围”的错误,但它是错误的。我正在尝试访问第16个元素,'args‘的长度是19。在第5行和第6行,我分别打印了索引和列表的元素,这些行的执行没有错误。
为什么我会得到这个错误?另外,第10行的打印报表没有打印,原因是什么?
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发布于 2021-07-25 20:42:33
这里的主要问题发生在您执行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)发布于 2021-07-25 21:00:29
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计数。
https://stackoverflow.com/questions/68518629
复制相似问题