![](/img/trans.png)
[英]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.