『转载』Python字典按值排序、包含字典的列表按字典值排序的方法

 

原文地址http://ghostfromheaven.iteye.com/blog/1563576

 

01 #-*- encoding=utf-8 -*-  
02 
03 import operator
04 #按字典值排序(默认为升序)  
05 x = {1:2, 3:4, 4:3, 2:1, 0:0}
06 sorted_x = sorted(x.iteritems(), key=operator.itemgetter(1))
07 print sorted_x
08 #[(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)]  
09 #如果要降序排序,可以指定reverse=True  
10 sorted_x = sorted(x.iteritems(), key=operator.itemgetter(1), reverse=True)
11 print sorted_x
12 #[(3, 4), (4, 3), (1, 2), (2, 1), (0, 0)]  
13 #或者直接使用list的reverse方法将sorted_x顺序反转  
14 #sorted_x.reverse()  
15 
16 #取代方法是,用lambda表达式  
17 sorted_x = sorted(x.iteritems(), key=lambda x : x[1])
18 print sorted_x
19 #[(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)]  
20 sorted_x = sorted(x.iteritems(), key=lambda x : x[1], reverse=True)
21 print sorted_x
22 #[(3, 4), (4, 3), (1, 2), (2, 1), (0, 0)]  
23 
24 #包含字典dict的列表list的排序方法与dict的排序类似,如下:  
25 x = [{‘name’:‘Homer’, ‘age’:39}, {‘name’:‘Bart’, ‘age’:10}]
26 sorted_x = sorted(x, key=operator.itemgetter(‘name’))
27 print sorted_x
28 #[{‘age’: 10, ‘name’: ‘Bart’}, {‘age’: 39, ‘name’: ‘Homer’}]  
29 sorted_x = sorted(x, key=operator.itemgetter(‘name’), reverse=True)
30 print sorted_x
31 #[{‘age’: 39, ‘name’: ‘Homer’}, {‘age’: 10, ‘name’: ‘Bart’}]  
32 sorted_x = sorted(x, key=lambda x : x[‘name’])
33 print sorted_x
34 #[{‘age’: 10, ‘name’: ‘Bart’}, {‘age’: 39, ‘name’: ‘Homer’}]  
35 sorted_x = sorted(x, key=lambda x : x[‘name’], reverse=True)
36 print sorted_x
37 #[{‘age’: 39, ‘name’: ‘Homer’}, {‘age’: 10, ‘name’: ‘Bart’}]

 

说点什么

avatar
  Subscribe  
提醒