【问题标题】:IndexError: list assignment index out of range PythonIndexError:列表分配索引超出范围Python
【发布时间】:2016-01-22 22:43:14
【问题描述】:
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

【问题讨论】:

    标签: python list python-3.x indexof


    【解决方案1】:

    问题是你原来有一个空列表:

    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)
    

    【讨论】:

      【解决方案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])
      

      【讨论】:

      • 你可以用g.get代替lambda x: g[x]
      【解决方案3】:

      此时,在循环开始时,highest_list 为空,因此没有第一个索引。您可以将highest_list 初始化为[0],以便始终存在至少一个“最大值”。

      也就是说,您可以更简单地完成此操作,如下所示:

      def mode(given_list):
          return max(set(given_list), key=given_list.count)
      

      这将根据每个项目的count() 在传递的given_list 中找到最高的项目。首先创建set 可确保每个项目只计算一次。

      【讨论】:

        猜你喜欢
        • 2018-10-21
        • 2020-02-13
        • 1970-01-01
        • 1970-01-01
        • 2018-03-19
        • 1970-01-01
        • 2022-11-27
        • 2020-09-17
        • 1970-01-01
        相关资源
        最近更新 更多