我正在嘗試對字典進行排序,我要遵循的順序是,首先,字典應該按值按升序排序,如果兩個或多個鍵的值相等,那么我想按鍵對字典進行排序按降序排列。這是代碼:dictionary = {0: 150, 1: 151, 2: 150, 3: 101, 4: 107}
print(sorted(dictionary.items(), key=lambda x: (x[1], x[0])))我希望輸出如下: [(3, 101), (4, 107), (2, 150), (0, 150), (1, 151)]但輸出是: [(3, 101), (4, 107), (0, 150), (2, 150), (1, 151)]
1 回答

守候你守候我
TA貢獻1802條經驗 獲得超10個贊
因為這里的值是數字的,所以你可以使用否定作為與反轉排序順序相同的效果:
sorted(dictionary.items(), key=lambda x: (x[1], -x[0]))
對于不能依賴數字值的更通用的情況,這里是一種可能的方法,盡管可能有更好的方法。
from functools import cmp_to_key
def cmp(a, b):
# https://stackoverflow.com/a/22490617/13596037
return (a > b) - (a < b)
def cmp_items(a, b):
"""
compare by second item forward, or if they are the same then use first item
in reverse direction (returns -1/0/1)
"""
return cmp(a[1], b[1]) or cmp(b[0], a[0])
dictionary = {0: 150, 1: 151, 2: 150, 3: 101, 4: 107}
print(sorted(dictionary.items(), key=cmp_to_key(cmp_items)))
添加回答
舉報
0/150
提交
取消