国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python實現字典排序、按照list中字典的某個key排序的方法示例

2020-02-16 00:12:09
字體:
來源:轉載
供稿:網友

本文實例講述了Python實現字典排序、按照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的區別在于當score均為90的時候,重新按照no排序

2.順序為從小到大,若在sorted函數的參數加上reverse = True則為從大到小

PS:這里再為大家推薦一款關于排序的演示工具供大家參考:

在線動畫演示插入/選擇/冒泡/歸并/希爾/快速排序算法過程工具:
http://tools.jb51.net/aideddesign/paixu_ys

更多關于Python相關內容感興趣的讀者可查看本站專題:《Python數據結構與算法教程》、《Python列表(list)操作技巧總結》、《Python編碼操作技巧總結》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》及《Python入門與進階經典教程》

希望本文所述對大家Python程序設計有所幫助。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 涟水县| 临猗县| 肥城市| 丰镇市| 辽阳县| 宜春市| 泰和县| 裕民县| 诸暨市| 炎陵县| 通海县| 洛川县| 伊春市| 龙江县| 扎兰屯市| 雅安市| 浦县| 中山市| 新津县| 康马县| 含山县| 满城县| 洪泽县| 新河县| 山西省| 文登市| 阜阳市| 东乡县| 新泰市| 霍山县| 高平市| 宝清县| 博客| 旅游| 湖南省| 嘉荫县| 宜城市| 赤水市| 双江| 辽阳县| 平遥县|