相关疑难解决方法(0)

如何按值对计数器进行排序? - 蟒蛇

除了对反向列表理解进行列表理解之外,还有一种pythonic方法可以按值对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)
Run Code Online (Sandbox Code Playgroud)

python sorting collections counter

107
推荐指数
4
解决办法
9万
查看次数

标签 统计

collections ×1

counter ×1

python ×1

sorting ×1