1 回答

TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超10個(gè)贊
因?yàn)檫@里的值是數(shù)字的,所以你可以使用否定作為與反轉(zhuǎn)排序順序相同的效果:
sorted(dictionary.items(), key=lambda x: (x[1], -x[0]))
對(duì)于不能依賴數(shù)字值的更通用的情況,這里是一種可能的方法,盡管可能有更好的方法。
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)))
添加回答
舉報(bào)