使用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 降序
這個用的比較多,先記錄一下,寫給自己看,
讀書和健身總有一個在路上
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/153385.html
標籤:Python
