简体   繁体   English

如何从python中的列表中获取最常见的元素

[英]How to get the most common element from a list in python

I'm having a list as shown here. 我有一个如此处所示的列表。 a=[1936,2401,2916,4761,9216,9216,9604,9801] I want to get the value which have more duplicates. a=[1936,2401,2916,4761,9216,9216,9604,9801]我想得到更多重复的值。 In here it is '9216' how can i get this value? 在这里它是'9216'我怎么能得到这个值? Thanks 谢谢

You can use collections.Counter for this: 您可以使用collections.Counter

from collections import Counter

a = [1936, 2401, 2916, 4761, 9216, 9216, 9604, 9801] 

c = Counter(a)

print(c.most_common(1)) # the one most common element... 2 would mean the 2 most common
[(9216, 2)] # a set containing the element, and it's count in 'a'

From the docs: 来自文档:

在此输入图像描述 在此输入图像描述

https://docs.python.org/2.7/library/collections.html#counter https://docs.python.org/2.7/library/collections.html#counter

from collections import Counter Counter(a).most_common(1) 来自收藏夹进口柜台柜台(a).most_common(1)

Here is another one not using counter 这是另一个不使用计数器的人

a=[1936,2401,2916,4761,9216,9216,9604,9801]
frequency = {}
for element in a:
    frequency[element] = frequency.get(element, 0) + 1
# create a list of keys and sort the list
# all words are lower case already
keyList = frequency.keys()
keyList.sort()
print "Frequency of each word in the word list (sorted):"
for keyElement in keyList:
    print "%-10s %d" % (keyElement, frequency[keyElement])

There's two standard library ways to do this: 有两种标准库方法可以做到这一点:

statistics.mode : statistics.mode

from statistics import mode
most_common = mode([3, 2, 2, 2, 1])  # 2
most_common = mode([3, 2])  # StatisticsError: no unique mode

collections.Counter.most_common : collections.Counter.most_common

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

Both are identical in terms of performance, but the first raises an exception when there is no unique most common element and the second returns the frequency as well. 两者在性能方面都是相同的,但是当没有唯一的最常见元素时,第一个引发异常,第二个也返回频率。

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

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