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

Bet*_*eth -1 python counter list

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

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

[0,2,1,1] = 2

[0,2,1,1,0] = 2
Run Code Online (Sandbox Code Playgroud)

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

the*_*eye 5

你可以使用这样collections.Countermost_common功能

from collections import Counter
print Counter([0, 0, 1, 2, 3, 0]).most_common(1)
# [(0, 3)]
Run Code Online (Sandbox Code Playgroud)

这为您提供了iterable中最常出现的项目.如果你只想要计数,你可以使用这样的max函数

print max(Counter([0, 0, 1, 2, 3, 0]).itervalues())
Run Code Online (Sandbox Code Playgroud)

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

print(max(Counter([0, 0, 1, 2, 3, 0]).values()))
Run Code Online (Sandbox Code Playgroud)