简体   繁体   English

如何修复Python中的“索引超出范围”错误?

[英]How to fix an 'index out of range' error in Python?

I would like to write en auxiliar function which is counting the occurences of every integer between 0 and li[-1], saying that li is a sorted list. 我想编写一个辅助函数,该函数对0和li [-1]之间的每个整数的出现进行计数,说li是一个有序列表。

I can't see my mistake... I know what this kind of error message means, but I don't know where the variable j is reaching a limit. 我看不到我的错误...我知道这种错误消息的含义,但是我不知道变量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

For example, with the input [2,4,4,4,7,8,8], the output should be [0,0,1,0,3,0,0,1,2] 例如,对于输入[2,4,4,4,7,8,8],输出应为[0,0,1,0,3,0,0,1,2]

I added "j < len(li)" to your code and now it works. 我在您的代码中添加了“ 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 can be passed an iteratable and will count each occurance, we can then use a simple comprehension to generate the result 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)]

Or if you wish to use the previous method of incrementing the values in a list, you already know the index in the list because it is equal to the integer value. 或者,如果您希望使用以前的方法来递增列表中的值,则您已经知道列表中的索引,因为它等于整数值。 We can simplify quite a bit 我们可以简化很多

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM