2015-09-26 74 views
0

我有一个列表,如下所示。 a=[1936,2401,2916,4761,9216,9216,9604,9801] 我想获得更多重复的值。在这里它是'9216'我怎么能得到这个值?由于如何从python列表中获取最常见的元素

+0

可能重复[如何找到一个列表的最常见的元素?](http://stackoverflow.com/questions/3594514/how-to -find,最常见的元素对的一列表) –

回答

1

您可以使用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' 

从文档:

enter image description here enter image description here

0

这里是不使用反另一个

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]) 
相关问题