2024-04-19 05:06:09 发布
网友
我想找出列表中最常见的元素出现的次数。例如:
[0,0,1,2,3,0] = 3 [0,2,1,1] = 2 [0,2,1,1,0] = 2
在Python中最有效的方法是什么?你知道吗
另一种选择
a_list = [0,2,1,1] a_list.count(max(a_list, key=a_list.count))
您可以使用collections.Counter的most_common函数,如下所示
collections.Counter
most_common
from collections import Counter print Counter([0, 0, 1, 2, 3, 0]).most_common(1) # [(0, 3)]
这将为您提供iterable中最常见的项。如果只需要计数,可以使用max函数,如下所示
max
print max(Counter([0, 0, 1, 2, 3, 0]).itervalues())
如果您使用的是Python3.x,那么
print(max(Counter([0, 0, 1, 2, 3, 0]).values()))
另一种选择
您可以使用
collections.Counter
的most_common
函数,如下所示这将为您提供iterable中最常见的项。如果只需要计数,可以使用
max
函数,如下所示如果您使用的是Python3.x,那么
相关问题 更多 >
编程相关推荐