获取最常见的值(-s)collections.Counter.most common()
使用 collections.Counter
计算 Mapping
的键是不可能的,但我们可以计算值 :
from collections import Counter
adict = {'a': 5, 'b': 3, 'c': 5, 'd': 2, 'e':2, 'q': 5}
Counter(adict.values())
# Out: Counter({2: 2, 3: 1, 5: 3})
最常见的元素可以通过 most_common
方法获得:
# Sorting them from most-common to least-common value:
Counter(adict.values()).most_common()
# Out: [(5, 3), (2, 2), (3, 1)]
# Getting the most common value
Counter(adict.values()).most_common(1)
# Out: [(5, 3)]
# Getting the two most common values
Counter(adict.values()).most_common(2)
# Out: [(5, 3), (2, 2)]