alv*_*vas 7 python collections counter dictionary multiset
可以如下访问计数器的最大值:
c = Counter()
c['foo'] = 124123
c['bar'] = 43
c['foofro'] =5676
c['barbar'] = 234
# This only prints the max key
print max(c), src_sense[max(c)] 
# print the max key of the value
x = max(src_sense.iteritems(), key=operator.itemgetter(1))[0]
print x, src_sense[x]
如果我想要一个降序计数的排序计数器怎么办?
如何访问第二个最大值,第三个或第N个最大值?
DSM*_*DSM 19
most_common(self, n=None) method of collections.Counter instance
    List the n most common elements and their counts from the most
    common to the least.  If n is None, then list all element counts.
    >>> Counter('abcdeabcdabcaba').most_common(3)
    [('a', 5), ('b', 4), ('c', 3)]
所以:
>>> c.most_common()
[('foo', 124123), ('foofro', 5676), ('barbar', 234), ('bar', 43)]
>>> c.most_common(2)[-1]
('foofro', 5676)
请注意,max(c)可能不会返回您想要的内容:迭代Counter遍历键是迭代,因此max(c) == max(c.keys()) == 'foofro',它是字符串排序后的最后一个.你需要做类似的事情
>>> max(c, key=c.get)
'foo'
得到(a)具有最大值的密钥.以类似的方式,你可以most_common完全放弃并自己做这种事:
>>> sorted(c, key=c.get)[-2]
'foofro'