第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

按值升序排序字典,按鍵降序排序

按值升序排序字典,按鍵降序排序

陪伴而非守候 2023-06-13 17:02:24
我正在嘗試對(duì)字典進(jìn)行排序,我要遵循的順序是,首先,字典應(yīng)該按值按升序排序,如果兩個(gè)或多個(gè)鍵的值相等,那么我想按鍵對(duì)字典進(jìn)行排序按降序排列。這是代碼: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貢獻(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)))


查看完整回答
反對(duì) 回復(fù) 2023-06-13
  • 1 回答
  • 0 關(guān)注
  • 121 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)