【问题标题】:How to find the 2nd max of a Counter - Python如何找到计数器的第二个最大值 - Python
【发布时间】:2013-03-28 23:03:51
【问题描述】:

可以这样访问计数器的最大值:

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]

如果我想要一个按降序计数的排序计数器怎么办?

如何访问第 2 个最大值、第 3 个或第 N 个最大值键?

【问题讨论】:

    标签: python collections dictionary counter multiset


    【解决方案1】:

    collections.Counter 实例的 most_common(self, n=None) 方法

    列出 n 个最常见的元素及其从最常见到最少的计数。如果 n 为 None,则列出所有元素计数。

    >>> 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'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-20
      • 2018-05-20
      • 1970-01-01
      • 1970-01-01
      • 2014-12-07
      • 2013-05-24
      相关资源
      最近更新 更多