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

首頁 > 編程 > Python > 正文

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

2020-01-04 13:47:04
字體:
來源:轉載
供稿:網友

本文實例講述了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則為從大到小

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


注:相關教程知識閱讀請移步到python教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 突泉县| 上饶市| 铁力市| 岢岚县| 陕西省| 拜泉县| 公安县| 黄梅县| 全州县| 阿尔山市| 扎鲁特旗| 邯郸市| 贵阳市| 左贡县| 上饶县| 阿尔山市| 天气| 云阳县| 四川省| 宾阳县| 碌曲县| 涟源市| 阜阳市| 巴林左旗| 仁布县| 青田县| 台中县| 罗田县| 荥经县| 集安市| 潢川县| 平昌县| 衡阳县| 西丰县| 和顺县| 光山县| 吉首市| 光山县| 合川市| 临澧县| 司法|