使用operator排序
按字典的值排序(默认为升序):
import operator
x = {1:2, 3:4, 4:3, 2:1, 0:0}
sorted_x = sorted(x.items(), key=operator.itemgetter(1))
print sorted_x) #[(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)]
如果要降序排序,指定参数reverse=True即可:
sorted_x = sorted(x.items(), key=operator.itemgetter(1), reverse=True)
print(sorted_x) #[(3, 4), (4, 3), (1, 2), (2, 1), (0, 0)]
#或者直接使用list的reverse方法将sorted_x顺序反转
sorted_x.reverse()
使用lambda表达式排序
sorted_x = sorted(x.items(), key=lambda x : x[1])
print(sorted_x) #[(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)]
sorted_x = sorted(x.items(), key=lambda x : x[1], reverse=True)
print(sorted_x) #[(3, 4), (4, 3), (1, 2), (2, 1), (0, 0)]
包含字典的列表排序方法与dict的排序类似,如下:
x = [{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}]
sorted_x = sorted(x, key=operator.itemgetter('name'))
print sorted_x #[{'age': 10, 'name': 'Bart'}, {'age': 39, 'name': 'Homer'}]
sorted_x = sorted(x, key=operator.itemgetter('name'), reverse=True)
print sorted_x #[{'age': 39, 'name': 'Homer'}, {'age': 10, 'name': 'Bart'}]
sorted_x = sorted(x, key=lambda x : x['name'])
print sorted_x) #[{'age': 10, 'name': 'Bart'}, {'age': 39, 'name': 'Homer'}]
sorted_x = sorted(x, key=lambda x : x['name'], reverse=True)
print sorted_x # [{'age': 39, 'name': 'Homer'}, {'age': 10, 'name': 'Bart'}]