#-*- encoding=utf-8 -*-排序
import operatorutf-8
#按字典值排序(默認爲升序)get
x = {1:2, 3:4, 4:3, 2:1, 0:0}it
sorted_x = sorted(x.iteritems(), key=operator.itemgetter(1))import
print sorted_xlambda
#[(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)]coding
#若是要降序排序,能夠指定reverse=True方法
sorted_x = sorted(x.iteritems(), key=operator.itemgetter(1), reverse=True)im
print sorted_xsort
#[(3, 4), (4, 3), (1, 2), (2, 1), (0, 0)]
#或者直接使用list的reverse方法將sorted_x順序反轉
#sorted_x.reverse()
#取代方法是,用lambda表達式
sorted_x = sorted(x.iteritems(), key=lambda x : x[1])
print sorted_x
#[(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)]
sorted_x = sorted(x.iteritems(), key=lambda x : x[1], reverse=True)
print sorted_x
#[(3, 4), (4, 3), (1, 2), (2, 1), (0, 0)]
#包含字典dict的列表list的排序方法與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'}]