除了对反向列表理解进行列表理解之外,还有一种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)
Martijn Piet.. 198
使用该Counter.most_common()
方法,它会为您排序项目:
>>> from collections import Counter >>> x = Counter({'a':5, 'b':3, 'c':7}) >>> x.most_common() [('c', 7), ('a', 5), ('b', 3)]
它会以最有效的方式这样做; 如果您要求使用前N而不是所有值,heapq
则使用a而不是直接排序:
>>> x.most_common(1) [('c', 7)]
在柜台外,可以根据key
功能调整分拣; .sort()
并且sorted()
都采用callable,允许您指定一个值来对输入序列进行排序; 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排序方法.
使用该Counter.most_common()
方法,它会为您排序项目:
>>> from collections import Counter >>> x = Counter({'a':5, 'b':3, 'c':7}) >>> x.most_common() [('c', 7), ('a', 5), ('b', 3)]
它会以最有效的方式这样做; 如果您要求使用前N而不是所有值,heapq
则使用a而不是直接排序:
>>> x.most_common(1) [('c', 7)]
在柜台外,可以根据key
功能调整分拣; .sort()
并且sorted()
都采用callable,允许您指定一个值来对输入序列进行排序; 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排序方法.
@MartijnPieters答案的一个相当不错的补充是返回按事件排序的字典,因为Collections.most_common
只返回一个元组.我经常将它与json输出结合用于方便的日志文件:
from collections import Counter, OrderedDict x = Counter({'a':5, 'b':3, 'c':7}) y = OrderedDict(x.most_common())
随着输出:
OrderedDict([('c', 7), ('a', 5), ('b', 3)]) { "c": 7, "a": 5, "b": 3 }
是:
>>> from collections import Counter >>> x = Counter({'a':5, 'b':3, 'c':7})
使用sorted关键字键和lambda函数:
>>> sorted(x.items(), key=lambda i: i[1]) [('b', 3), ('a', 5), ('c', 7)] >>> sorted(x.items(), key=lambda i: i[1], reverse=True) [('c', 7), ('a', 5), ('b', 3)]
这适用于所有词典.但是Counter
有一个特殊功能,它已经为您提供了排序项目(从最常见,到最不频繁).它被称为most_common()
:
>>> x.most_common() [('c', 7), ('a', 5), ('b', 3)] >>> list(reversed(x.most_common())) # in order of least to most [('b', 3), ('a', 5), ('c', 7)]
您还可以指定要查看的项目数:
>>> x.most_common(2) # specify number you want [('c', 7), ('a', 5)]