本文实例讲述了Python通过公共键对字典列表排序算法。分享给大家供大家参考,具体如下:
问题:想根据一个或多个字典中的值来对列表排序
解决方案:利用operator模块中的itemgetter()
函数对这类结构进行排序是非常简单的。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
# Sort a list of a dicts on a common key rows = [ { 'fname' : 'Brian' , 'lname' : 'Jones' , 'uid' : 1003 }, { 'fname' : 'David' , 'lname' : 'Beazley' , 'uid' : 1002 }, { 'fname' : 'John' , 'lname' : 'Cleese' , 'uid' : 1001 }, { 'fname' : 'Big' , 'lname' : 'Jones' , 'uid' : 1004 } ] from operator import itemgetter rows_by_fname = sorted (rows, key = itemgetter( 'fname' )) rows_by_uid = sorted (rows, key = itemgetter( 'uid' )) from pprint import pprint print ( "Sorted by fname:" ) pprint(rows_by_fname) #pprint模块的pprint()提供了打印出任何python数据结构类和方法。 print ( "Sorted by uid:" ) pprint(rows_by_uid) rows_by_lfname = sorted (rows, key = itemgetter( 'lname' , 'fname' )) print ( "Sorted by lname,fname:" ) pprint(rows_by_lfname) |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
>>> = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = RESTART = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = >>> Sorted by fname: [{ 'fname' : 'Big' , 'lname' : 'Jones' , 'uid' : 1004 }, { 'fname' : 'Brian' , 'lname' : 'Jones' , 'uid' : 1003 }, { 'fname' : 'David' , 'lname' : 'Beazley' , 'uid' : 1002 }, { 'fname' : 'John' , 'lname' : 'Cleese' , 'uid' : 1001 }] Sorted by uid: [{ 'fname' : 'John' , 'lname' : 'Cleese' , 'uid' : 1001 }, { 'fname' : 'David' , 'lname' : 'Beazley' , 'uid' : 1002 }, { 'fname' : 'Brian' , 'lname' : 'Jones' , 'uid' : 1003 }, { 'fname' : 'Big' , 'lname' : 'Jones' , 'uid' : 1004 }] Sorted by lname,fname: [{ 'fname' : 'David' , 'lname' : 'Beazley' , 'uid' : 1002 }, { 'fname' : 'John' , 'lname' : 'Cleese' , 'uid' : 1001 }, { 'fname' : 'Big' , 'lname' : 'Jones' , 'uid' : 1004 }, { 'fname' : 'Brian' , 'lname' : 'Jones' , 'uid' : 1003 }] >>> |
补充说明:
有时候会利用lambda表达式来取代itemgetter()
的功能:但是利用itemgetter()
会运行的更快一些,所以考虑性能的话,应该使用itemgetter()
。
1
2
|
rows_by_fname = sorted (rows, key = lambda r:r[ 'fname' ]) rows_by_uid = sorted (rows, key = lambda r:r[ 'uid' ]) |
最后,本节展示的技术同样适用于min()
和max()
这样的函数:
1
2
3
4
5
6
7
|
>>> min (rows, key = itemgetter( 'uid' )) { 'lname' : 'Cleese' , 'fname' : 'John' , 'uid' : 1001 } >>> max (rows, key = itemgetter( 'uid' )) { 'lname' : 'Jones' , 'fname' : 'Big' , 'uid' : 1004 } >>> itemgetter( 'uid' ) <operator.itemgetter object at 0x023532F0 > >>> |
(代码摘自《Python Cookbook》)
希望本文所述对大家Python程序设计有所帮助。
原文链接:http://www.cnblogs.com/apple2016/p/5747116.html