我有一个如此处所示的列表。 a=[1936,2401,2916,4761,9216,9216,9604,9801]
我想获得更多重复的值。在这里它是' 9216'我怎么能得到这个价值?感谢
答案 0 :(得分:5)
您可以使用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'
来自文档:
答案 1 :(得分:0)
https://docs.python.org/2.7/library/collections.html#counter
来自集合导入计数器 计数器的(a).most_common(1)
答案 2 :(得分: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])
答案 3 :(得分:0)
有两种标准的库方式可以做到这一点:
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
:
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
两者在性能上是相同的,但是第一个在没有唯一最常见的元素时引发异常,第二个也返回频率。