Use the Counter.most_common() method http://docs.python.org/library/collections.html#collections.Counter.most_common,它会对项目进行排序for you:
>>> from collections import Counter
>>> x = Counter({'a':5, 'b':3, 'c':7})
>>> x.most_common()
[('c', 7), ('a', 5), ('b', 3)]
它将以尽可能最有效的方式做到这一点;如果您要求前 N 个值而不是所有值,则heapq
使用而不是直接排序:
>>> x.most_common(1)
[('c', 7)]
在柜台之外,排序始终可以根据key
功能;.sort()
and sorted()
两者都可以调用,让您指定一个值来对输入序列进行排序;sorted(x, key=x.get, reverse=True)
会给你相同的排序x.most_common()
,但只返回键,例如:
>>> sorted(x, key=x.get, reverse=True)
['c', 'a', 'b']
或者您可以仅对给定的值进行排序(key, value)
pairs:
>>> sorted(x.items(), key=lambda pair: pair[1], reverse=True)
[('c', 7), ('a', 5), ('b', 3)]
See the Python 排序指南 http://docs.python.org/howto/sorting.html了解更多信息。