IndexError: list assignment index out of range Python
IndexError: list assignment index out of range Python
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)
就获得模式而言,您可以使用集合库中的计数器
from collections import Counter
x = [0, 1, 2, 0, 1, 0] #0 is the mode
g = Counter(x)
mode = max(g, key = lambda x: g[x])
此时,在循环开始时,highest_list
为空,因此没有第一个索引。您可以将 highest_list
初始化为 [0]
,这样总有至少一个 "highest value."
也就是说,您可以更简单地完成此操作,如下所示:
def mode(given_list):
return max(set(given_list), key=given_list.count)
这将根据每个项目的 count()
在传递的 given_list
中找到最高的项目。先做一个set
保证每一项只算一次
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)
就获得模式而言,您可以使用集合库中的计数器
from collections import Counter
x = [0, 1, 2, 0, 1, 0] #0 is the mode
g = Counter(x)
mode = max(g, key = lambda x: g[x])
此时,在循环开始时,highest_list
为空,因此没有第一个索引。您可以将 highest_list
初始化为 [0]
,这样总有至少一个 "highest value."
也就是说,您可以更简单地完成此操作,如下所示:
def mode(given_list):
return max(set(given_list), key=given_list.count)
这将根据每个项目的 count()
在传递的 given_list
中找到最高的项目。先做一个set
保证每一项只算一次