2016-01-22 134 views
1
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]) 

该代码旨在计算给定列表的模式。我不明白我出错的地方。IndexError:列表分配索引超出范围Python

准确的错误我正在收到。

line 30, in mode 
    highest_list[0] = given_list[x] 
IndexError: list assignment index out of range 

回答

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) 
1

至于获取模式,你可以使用从库

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]) 
+0

您可以使用'g.get'而不是'lambda x:g [x]'。 – TigerhawkT3

0

在这一点上,集合了一个计数器,在循环的开始,highest_list是空的,所以没有第一个索引。您可以将highest_list初始化为[0],以便始终存在至少一个“最高值”。

这就是说,你可以更简单地实现这一点,如下所示:

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

这会发现在通过given_list最高的项目,基于每个项目的count()在里面。首先制作set确保每个项目只计算一次。

相关问题