我有以下字典,按值递增排序。
>>> x = {'foo': 2.01, 'bar': 4.11, 'qux':3.2, 'ail':1.2, 'dfa':0.03}
>>> sorted_x = sorted(x.iteritems(), key=operator.itemgetter(1))
>>> sorted_x
[('dfa', 0.029999999999999999), ('ail', 1.2), ('foo', 2.0099999999999998), ('qux', 3.2000000000000002), ('bar', 4.1100000000000003)]
如何按价值降序排序? 我试过这个,但没有打印
>>> sorted_x.reverse()
>>>
答案 0 :(得分:3)
您可以在排序时使用reverse=True
:
>>> sorted(x.iteritems(), key=operator.itemgetter(1), reverse=True)
[('bar', 4.11), ('qux', 3.2), ('foo', 2.01), ('ail', 1.2), ('dfa', 0.03)]
答案 1 :(得分:1)
In [143]:
import operator
x = {'foo': 2.01, 'bar': 4.11, 'qux':3.2, 'ail':1.2, 'dfa':0.03}
sorted_x = sorted(x.iteritems(), key=operator.itemgetter(1), reverse=True)
sorted_x
Out[143]:
[('bar', 4.11), ('qux', 3.2), ('foo', 2.01), ('ail', 1.2), ('dfa', 0.03)]
答案 2 :(得分:1)
试试这个:
>>> x = {'foo': 2.01, 'bar': 4.11, 'qux':3.2, 'ail':1.2, 'dfa':0.03}
>>> sorted_x = sorted(x.iteritems(), key=operator.itemgetter(1), reverse=True)
>>> sorted_x
[('bar', 4.11), ('qux', 3.2), ('foo', 2.01), ('ail', 1.2), ('dfa', 0.03)]