如何找到Counter-Python的第二个max

2024-05-29 09:47:31 发布

您现在位置: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]

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

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


Tags: thekeysrconlyfoocounter计数器bar
1条回答
网友
1楼 · 发布于 2024-05-29 09:47:31
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'

相关问题 更多 >

    热门问题