def mode(given_list):
highest_list = []
highest = 0
index = 0
for x in range(0, len(given_list)):
occurrences = given_list.count(given_list[x])
if occurrences > highest:
highest = occurrences
highest_list[0] = given_list[x]
elif occurrences == highest:
highest_list.append(given_list[x])
该代码旨在计算出给定列表的模式。我不明白我哪里出了问题。
我收到的确切错误。
line 30, in mode
highest_list[0] = given_list[x]
IndexError: list assignment index out of range
最佳答案
问题是你原来有一个空列表:
highest_list = []
然后在循环中尝试在索引 0 处访问它:
highest_list[0] = ...
这是不可能的,因为它是一个空列表,因此在位置 0 处不可索引。
查找列表模式的更好方法是使用 collections.Counter
对象:
>>> from collections import Counter
>>> L = [1,2,3,3,4]
>>> counter = Counter(L)
>>> max(counter, key=counter.get)
3
>>> [(mode, n_occurrences)] = counter.most_common(1)
>>> mode, n_occurrences
(3, 2)
关于python - 索引错误: list assignment index out of range Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34957176/