2015-09-26 95 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])