集合的最大值.计数器



collections.Counter上的最大值与直觉相反,我想找到字符串中出现最多的字符。

>>> from collections import Counter
>>> c = Counter('aaaabbbcc')
>>> max(c)
'c'
>>> c
Counter({'a': 4, 'b': 3, 'c': 2})

我知道我应该使用most_common,但它的使用似乎是人为的。

>>> c.most_common(1)[0][0]
'a'

是否有支持计数器上的最大值的情况?

您可以使用max:的key参数

max(c, key=c.get)

输出:'a'

注意。Counter.most_common执行排序,因此以这种方式使用max也应该更快(快速测试告诉我,小型计数器就是这种情况,而大型计数器的差异有限(

max with key似乎比most_common 更快

>>> from collections import Counter
>>> import timeit
>>> s0 = 'aaaabbbcc'
>>> s1 = s0[:] * 100
>>> def f_max(s): return max((c := Counter(s)), key=c.get)
>>> def f_common(s): return Counter(s).most_common(1)[0][0]
>>> timeit.repeat("f_max(s1)", "from __main__ import f_max, f_common, s1", number=10000)
[0.32935670800000594, 0.32097511900002473, 0.3285609399999885, 0.3300831690000052, 0.326068628999991]
>>> timeit.repeat("f_common(s1)", "from __main__ import f_max, f_common, s1", number=10000)
[0.3436732490000054, 0.3355550489999928, 0.34284031400000003, 0.343095218000002, 0.34329394300002036]
>>> 

最新更新