Python實(shí)現(xiàn)字典排序、按照list中字典的某個key排序的方法示例
本文實(shí)例講述了Python實(shí)現(xiàn)字典排序、按照list中字典的某個key排序的方法。分享給大家供大家參考,具體如下:
1.給字典按照value按照從大到小排序
排序
dict = {'a':21, 'b':5, 'c':3, 'd':54, 'e':74, 'f':0}
new_dict = sorted(dict.iteritems(), key=lambda d:d[1], reverse = True)
print new_dict
輸出:
[('e', 74), ('d', 54), ('a', 21), ('b', 5), ('c', 3), ('f', 0)]
2. python按照list中的字典的某key排序:
例子:
s=[
{"no":28,"score":90},
{"no":25,"score":90},
{"no":1,"score":100},
{"no":2,"score":20},
]
print "original s: ",s
# 單級排序,僅按照score排序
new_s = sorted(s,key = lambda e:e.__getitem__('score'))
print "new s: ", new_s
# 多級排序,先按照score,再按照no排序
new_s_2 = sorted(new_s,key = lambda e:(e.__getitem__('score'),e.__getitem__('no')))
print "new_s_2: ", new_s_2
輸出:
original s: [{'score': 90, 'no': 28}, {'score': 90, 'no': 25}, {'score': 100, 'no': 1}, {'score': 20, 'no': 2}]
new s: [{'score': 20, 'no': 2}, {'score': 90, 'no': 28}, {'score': 90, 'no': 25}, {'score': 100, 'no': 1}]
new_s_2: [{'score': 20, 'no': 2}, {'score': 90, 'no': 25}, {'score': 90, 'no': 28}, {'score': 100, 'no': 1}]
說明
1.new_s和new_s2的區(qū)別在于當(dāng)score均為90的時(shí)候,重新按照no排序
2.順序?yàn)閺男〉酱?若在sorted函數(shù)的參數(shù)加上reverse = True則為從大到小
PS:這里再為大家推薦一款關(guān)于排序的演示工具供大家參考:
在線動畫演示插入/選擇/冒泡/歸并/希爾/快速排序算法過程工具:
http://tools.jb51.net/aideddesign/paixu_ys
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python列表(list)操作技巧總結(jié)》、《Python編碼操作技巧總結(jié)》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》及《Python入門與進(jìn)階經(jīng)典教程》
希望本文所述對大家Python程序設(shè)計(jì)有所幫助。
相關(guān)文章
python查詢文件夾下excel的sheet名代碼實(shí)例
這篇文章主要介紹了python查詢文件夾下excel的sheet名方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-04-04
Python 實(shí)現(xiàn)隨機(jī)數(shù)詳解及實(shí)例代碼
這篇文章主要介紹了Python 實(shí)現(xiàn)隨機(jī)數(shù)詳解及實(shí)例代碼的相關(guān)資料,需要的朋友可以參考下2017-04-04
Python替換月份為英文縮寫的實(shí)現(xiàn)方法
今天小編就為大家分享一篇Python替換月份為英文縮寫的實(shí)現(xiàn)方法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-07-07
python 動態(tài)加載的實(shí)現(xiàn)方法
腳本語言都有一個優(yōu)點(diǎn),就是動態(tài)加載,python也有這個特性。這篇文章主要介紹了python 動態(tài)加載的實(shí)現(xiàn)方法,需要的朋友可以參考下2017-12-12
python將MongoDB里的ObjectId轉(zhuǎn)換為時(shí)間戳的方法
這篇文章主要介紹了python將MongoDB里的ObjectId轉(zhuǎn)換為時(shí)間戳的方法,涉及Python操作MongoDB及字符串轉(zhuǎn)換的技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-03-03

