繁体   English   中英

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

[英]How to find the maximum number of times that the most common item in a list appears?

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

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

[0,2,1,1] = 2

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

在Python中最有效的方法是什么?

您可以使用collections.Countermost_common函数,如下所示

from collections import Counter
print Counter([0, 0, 1, 2, 3, 0]).most_common(1)
# [(0, 3)]

这为您提供了迭代中最常出现的项目。 如果只需要计数,可以使用max函数,如下所示

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

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

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

替代;

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM