gpt4 book ai didi

python - 如何按值对计数器进行排序? - Python

转载 作者:IT老高 更新时间:2023-10-28 21:08:10 30 4
gpt4 key购买 nike

除了对反向列表推导进行列表推导之外,是否有一种 Python 方法可以按值对 Counter 进行排序?如果是这样,它比这更快:

>>> from collections import Counter
>>> x = Counter({'a':5, 'b':3, 'c':7})
>>> sorted(x)
['a', 'b', 'c']
>>> sorted(x.items())
[('a', 5), ('b', 3), ('c', 7)]
>>> [(l,k) for k,l in sorted([(j,i) for i,j in x.items()])]
[('b', 3), ('a', 5), ('c', 7)]
>>> [(l,k) for k,l in sorted([(j,i) for i,j in x.items()], reverse=True)]
[('c', 7), ('a', 5), ('b', 3)

最佳答案

使用 Counter.most_common() method ,它会为您对项目进行排序:

>>> from collections import Counter
>>> x = Counter({'a':5, 'b':3, 'c':7})
>>> x.most_common()
[('c', 7), ('a', 5), ('b', 3)]

它将以最有效的方式进行;如果您要求 Top N 而不是所有值,则使用 heapq 而不是直接排序:

>>> x.most_common(1)
[('c', 7)]

在计数器之外,排序总是可以基于 key 函数进行调整; .sort()sorted() 都采用可调用函数,可让您指定对输入序列进行排序的值; sorted(x, key=x.get, reverse=True) 会给你与 x.most_common() 相同的排序,但只返回键,例如:

>>> sorted(x, key=x.get, reverse=True)
['c', 'a', 'b']

或者您可以只对给定的 (key, value) 对的值进行排序:

>>> sorted(x.items(), key=lambda pair: pair[1], reverse=True)
[('c', 7), ('a', 5), ('b', 3)]

Python sorting howto了解更多信息。

关于python - 如何按值对计数器进行排序? - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20950650/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com