2013-04-06 54 views
2

計數器的最大可接這樣:如何找到一個反的第二個最大 - Python的

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] 

,如果我想在遞減計數排序的計數器是什麼?

我該如何訪問第二個最大值,或第3個或第N個最大鍵?

回答

7
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' 
相關問題