【发布时间】:2015-09-26 11:10:54
【问题描述】:
我有一个如此处所示的列表。 a=[1936,2401,2916,4761,9216,9216,9604,9801]
我想获得具有更多重复项的值。在这里是'9216' 我怎样才能得到这个值?谢谢
【问题讨论】:
标签: python list python-3.x
我有一个如此处所示的列表。 a=[1936,2401,2916,4761,9216,9216,9604,9801]
我想获得具有更多重复项的值。在这里是'9216' 我怎样才能得到这个值?谢谢
【问题讨论】:
标签: python list python-3.x
有两种标准库方法可以做到这一点:
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
两者在性能方面是相同的,但是当没有唯一的最常见元素时,第一个会引发异常,而第二个也会返回频率。
【讨论】:
这是另一个没有使用计数器的
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])
【讨论】:
https://docs.python.org/2.7/library/collections.html#counter
从集合导入计数器 计数器(a).most_common(1)
【讨论】: