我有一本字典,我希望首先按值按降序排序,然后按鍵按遞增(字母)順序排序
我的輸入看起來像
{('shall', 'prove'): 1, ('shall', 'not'): 1, ('shall', 'go'): 1, ('shall', 'fight'): 7, ('shall', 'defend'): 1, ('shall', 'never'): 1}
我希望我的輸出看起來像
[(('shall', 'fight'), 7), (('shall', 'defend'), 1), (('shall', 'go'), 1), (('shall', 'never'), 1), (('shall', 'not'), 1) (('shall', 'prove'), 1), ]
我試過了
def sort_dict(dictionary):
unsorted_list = list(dictionary.items())
sorted_list = sorted(unsorted_list, key=operator.itemgetter(1), reverse=True)
return sorted_list
按值遞減排序,但我不確定如何同時按鍵遞增排序。如果我需要提供任何進一步的資訊,請告訴我。謝謝!
uj5u.com熱心網友回復:
按降序對值進行排序與??按升序對負值進行排序相同。排序可以一次性完成,方法是創建一個自定義元組,其中包含要根據優先級排序的值,即先值后鍵。
sorted(dictionary.items(), key=lambda x:(-x[1],) x[0])
[(('shall', 'fight'), 7), (('shall', 'defend'), 1), (('shall', 'go'), 1), (('shall', 'never'), 1), (('shall', 'not'), 1), (('shall', 'prove'), 1)]
uj5u.com熱心網友回復:
您可以利用 Python 的排序穩定這一事實,分兩步執行排序。首先按最不重要的組件值排序,然后按最重要的組件值排序:
dictionary = {('shall', 'prove'): 1, ('shall', 'not'): 1,
('shall', 'go'): 1, ('shall', 'fight'): 7,
('shall', 'defend'): 1, ('shall', 'never'): 1}
byKeyAscending = sorted(dictionary.items())
sortedDict = sorted(byKeyAscending,key=lambda kv:kv[1],reverse=True)
[(('shall', 'fight'), 7), (('shall', 'defend'), 1),
(('shall', 'go'), 1), (('shall', 'never'), 1),
(('shall', 'not'), 1), (('shall', 'prove'), 1)]
對于您的特定示例,假設值是數字,您可以使用否定來反轉順序并在一個步驟中執行排序:
sortedDict=sorted(dictionary.items(),key=lambda kv:(-kv[1],kv[0]))
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/375715.html
上一篇:計算字典鍵出現在資料框中的次數
下一篇:使用字典計算串列串列中的元素
