[英]How to fix “IndexError: list assignment index out of range” error in Python?
[英]How to fix an 'index out of range' error in Python?
我想编写一个辅助函数,该函数对0和li [-1]之间的每个整数的出现进行计数,说li是一个有序列表。
我看不到我的错误...我知道这种错误消息的含义,但是我不知道变量j在哪里达到极限。
def aux_compter_occurence(li):
resu = [0] * (li[-1]+1)
i = 0
j = 0
while i < (li[-1] + 1):
while li[j] == i:
resu[i] += 1
j +=1
i += 1
return resu
例如,对于输入[2,4,4,4,7,8,8],输出应为[0,0,1,0,3,0,0,1,2]
我在您的代码中添加了“ j <len(li)”,现在可以使用了。
def aux_compter_occurence(li):
resu = [0] * (li[-1]+1)
i = 0
j = 0
while i < (li[-1] + 1):
while j < len(li) and li[j] == i:
resu[i] += 1
j +=1
i += 1
return resu
collections.Counter
可以通过一个可重复的,并会计算每次出现,我们可以用一个简单的理解,产生的结果
import collections
def aux_compter_occurence(li):
counts = collections.Counter(li)
return [counts.get(i, 0) for i in range(li[-1] + 1)]
或者,如果您希望使用以前的方法来递增列表中的值,则您已经知道列表中的索引,因为它等于整数值。 我们可以简化很多
def aux_compter_occurence(li):
resu = [0] * (li[-1] + 1)
for i in li:
resu[i] += 1
return resu
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.