Python cookbook(資料結構與演算法)通過公用鍵對字典列表排序演算法樣本,pythoncookbook

來源:互聯網
上載者:User

Python cookbook(資料結構與演算法)通過公用鍵對字典列表排序演算法樣本,pythoncookbook

本文執行個體講述了Python通過公用鍵對字典列表排序演算法。分享給大家供大家參考,具體如下:

問題:想根據一個或多個字典中的值來對列表排序

解決方案:利用operator模組中的itemgetter()函數對這類結構進行排序是非常簡單的。

# Sort a list of a dicts on a common keyrows = [  {'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 itemgetterrows_by_fname = sorted(rows, key=itemgetter('fname'))rows_by_uid = sorted(rows, key=itemgetter('uid'))from pprint import pprintprint("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》)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.