python dic字典排序


使用lambda匿名函數來實現。

>>> dic1 = {'a':1,'b':2,'e':5,'d':4,'c':3}
>>> result = sorted(dic1.items(), key = lambda x :(x[1]))
>>> result
[('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)]
>>> result = sorted(dic1.items(), key = lambda x :(-x[1]))
>>> result
[('e', 5), ('d', 4), ('c', 3), ('b', 2), ('a', 1)]
>>> dic1
{'a': 1, 'b': 2, 'e': 5, 'd': 4, 'c': 3}
>>> result = sorted(dic1.items(), key = lambda x :(x[0]))
>>> result
[('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)]
>>> result = sorted(dic1.items(), key = lambda x :(x[0]),reverse = True)
>>> result
[('e', 5), ('d', 4), ('c', 3), ('b', 2), ('a', 1)]

#x[0] 用字典的第一位排序
#x[1] 用字典的第二位排序
#-x[0] 用第一位的負數排序

默認是升序
reverse = True 降序

這個用的比較多,先記錄一下。寫給自己看。


讀書和健身總有一個在路上


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM