如何查找列表中最常见项目的最大显示次数?

时间:2014-08-05 15:53:26

标签: python list counter

我想查找列表中最常见元素出现的次数。例如:

[0,0,1,2,3,0] = 3

[0,2,1,1] = 2

[0,2,1,1,0] = 2

在Python中执行此操作的最有效方法是什么?

2 个答案:

答案 0 :(得分:5)

您可以使用collections.Counter的{​​{1}}功能,例如

most_common

这为您提供了iterable中最常出现的项目。如果您只想要计数,可以使用from collections import Counter print Counter([0, 0, 1, 2, 3, 0]).most_common(1) # [(0, 3)] 函数,就像这样

max

如果您使用的是Python 3.x,那么

print max(Counter([0, 0, 1, 2, 3, 0]).itervalues())

答案 1 :(得分:1)

替代方案;

a_list = [0,2,1,1]
a_list.count(max(a_list, key=a_list.count))