在列表中找到出现次数最多的项目


问题内容

在Python中,我有一个列表:

L = [1, 2, 45, 55, 5, 4, 4, 4, 4, 4, 4, 5456, 56, 6, 7, 67]

我想确定出现次数最多的项目。我能够解决它,但我需要最快的方法。我知道有一个很好的Pythonic答案。


问题答案:

这是defaultdict适用于Python 2.5及更高版本的解决方案:

from collections import defaultdict

L = [1,2,45,55,5,4,4,4,4,4,4,5456,56,6,7,67]
d = defaultdict(int)
for i in L:
    d[i] += 1
result = max(d.iteritems(), key=lambda x: x[1])
print result
# (4, 6)
# The number 4 occurs 6 times

请注意,是否L = [1, 2, 45, 55, 5, 4, 4, 4, 4, 4, 4, 5456, 7, 7, 7, 7, 7, 56, 6, 7, 67] 有六个4s和六个7s。但是,结果将是(4, 6) 六个4s。