码迷,mamicode.com
首页 > 编程语言 > 详细

【python cookbook】【数据结构与算法】13.通过公共键对字典列表排序

时间:2016-08-07 21:22:34      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:

问题:想根据一个或多个字典中的值来对列表排序

解决方案:利用operator模块中的itemgetter()函数对这类结构进行排序是非常简单的。

# 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)
>>> ================================ 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()。

rows_by_fname = sorted(rows, key=lambda r:r[fname])
rows_by_uid = sorted(rows, key=lambda r:r[uid])

最后,本节展示的技术同样适用于min()和max()这样的函数:

>>> 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】【数据结构与算法】13.通过公共键对字典列表排序

标签:

原文地址:http://www.cnblogs.com/apple2016/p/5747116.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!