python - 索引错误: list assignment index out of range Python

标签 python list python-3.x indexof

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/

相关文章:

python - 函数参数类型设置返回 SyntaxError

Python:什么库是 'standard libraries' ?

python - 如何获取每个字符串变体以及每个位置的可能性列表

python - 为什么 Python 扩展输出 [[...]]

python - 在 matplotlib 上设置高度和宽度

python - 以特定顺序调用函数列表?

python - 计算嵌套列表中的元素出现次数

javascript - 使用前端 javascript 访问绑定(bind)到 Bokeh 字形的数据

python - 使用索引手动切片列表,Python

python - "requests.exceptions.ConnectionError: (' 连接中止。 ', RemoteDisconnected(' 远端关闭连接无响应 ',))"