[英]Why is it Showing List index Out Of Range Error?
我試圖僅使用單個列表而不是字典來計算測試列表中僅正整數元素的出現次數,以減少空間復雜度。 但不幸的是,下面的代碼失敗了。 誰能解釋為什么?
def count_items_from_list2(List):
count =[0]*max(List)
'''
from collections import defaultdict
count = defaultdict(lambda:0)
'''
distinct_element_count=0
for i in range(len(List)):
if count[List[i]]==0:
distinct_element_count+=1
count[List[i]]+=1
return [(List[i],count[List[i]]) for i in range(len(List))],distinct_element_count
List = [5,4,8,2,4,9,22,50,79,22,50,50,66,33,8,4]
items_count,distinct_elements = count_items_from_list2(List)
print("Count of all items: ",items_count)
print("No of distinct elements: ",distinct_elements)
您需要在此處添加 1:
count = [0] * (max(List) + 1)
索引從 0 開始,在您的代碼中,當您通過索引 79 訪問時,它會失敗,因為最后一個是 78。
代替:
count =[0]*max(List)
和:
count =[0]*(max(List) + 1)
你沒有給 count 正確的大小:
def count_items_from_list2(List):
count =[0] * (max(List) + 1)
您還可以使用collections.Counter :
from collections import Counter
List = [5,4,8,2,4,9,22,50,79,22,50,50,66,33,8,4]
print(Counter(List).keys()) # equals to list(set(List ))
print(Counter(List).values()) # counts the element's frequency
輸出:
dict_keys([5, 4, 8, 2, 9, 22, 50, 79, 66, 33])
dict_values([1, 3, 2, 1, 1, 2, 3, 1, 1, 1])
為什么顯示列表索引超出范圍錯誤?
您可以嘗試打印傳遞給您的列表count
的索引。
問題在於您的行count = [0] * max(List)
。
您需要按max(List) + 1
縮放您的count
列表。 Python(以及許多其他編程語言)中的索引從 0 開始。我嘗試運行您的代碼,但在嘗試訪問count
列表中的第 79 個索引時失敗。 79 恰好是列表List
的最大整數,它的對應索引應該是79
。 但是,由於您的count
列表的大小為 79,因此它的最后一個索引將為 78(因為索引從 0 開始)。
count = [0] * (max(List) + 1)
我假設你只有positive integers
。 如果你List
沒有 0 int,那么你也可以這樣做:
if count[List[i] - 1] == 0:
distinct_element_count += 1
count[List[i] - 1] += 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.