簡體   English   中英

在 Python 字典中排序 function

[英]Sorted function in Python dictionary

我有一本字典,如果有任何值平局,我需要打印首先按“值”排序的字典內容,然后我需要使用“鍵”作為平局斷路器,以便打印具有相同值的鍵字母順序。

final = OrderedDict(sorted(mydict.items(), key=lambda x: (x[1], x[0]), reverse=True))

for key, value in final.items():
    print(f'{key} : {value}')

但是當打印命令運行時,它將顯示 output 就像沒有按預期排序相同的值:

Action : 3
Romance : 2
Horror : 2
History : 2
Comedy : 2
Adventure : 1

它應該打印的方式必須是這樣的:

Action : 3
Comedy : 2
History : 2
Horror : 2
Romance : 2
Adventure : 1

關於如何糾正這個問題的任何想法?

{k: v for k, v in sorted(mydict.items(), key=lambda item: (-item[1], item[0]), reverse=False)}

在根據key對序列進行排序應用reverse 您只希望x[1]上的比較被反轉,而不是最終排序。 我將使用functools.cmp_to_key將比較 function 轉換為密鑰 function。

from functools import cmp_to_key

# Redefined from Python 2 since Python 3 dropped it
def cmp(x, y):
    return -1 if x < y else 0 if x == y else 1

def genre_sort(x, y):
    # A bigger count is a smaller genre; otherwise, sort alphabetically
    # by name
    return cmp(y[1], x[1]) or cmp(x[0], y[0])
    
final = OrderedDict(sorted(mydict.items(), key=cmp_to_key(genre_sort)))

您只想反轉x[1]的排序,所以不要在這里傳遞reverse=True ,而是使用負數技巧:

final = OrderedDict(sorted(mydict.items(), key=lambda x: (-x[1], x[0])))

當已經有其他三個答案時,為什么要這個答案?

在我看來,其他答案都沒有暴露問題中描述的問題的核心,順便說一句,這里已經充分回答了:https://stackoverflow.com/questions/20145842/python-sorting-by-multiple-criteria 在這里 https://stackoverflow.com/questions/55866762/how-to-sort-a-list-of-strings-in-reverse-order-without-using-reverse-true-parame使其成為關閉的候選者作為副本。

Python 的特點是可以解決以不同排序順序對列進行排序的問題,即

Python 的排序是穩定的,允許您使用連續排序,首先使用最右邊的標准,然后是下一個,依此類推(Martijn Pieters)

Python 的排序算法是穩定的,這意味着相等的元素保持它們的相對順序。 因此,您可以對第二個元素使用第一次排序(按升序排序),然后再次排序,僅對第一個元素並以相反的順序排序。

我已將問題中列出的字典更改為僅包含字符串值,不允許在鍵 function 中使用帶有負數值的“技巧”,以實現所需的結果來演示上述內容。

下面的代碼:

mydict = { 
    'Romance'   : '2', 
    'Adventure' : '1', 
    'Action'    : '3', 
    'Horror'    : '2', 
    'History'   : '2',
    'Comedy'    : '2',
}
mylist = list(mydict.items())
print(mylist)
print()
mylist = sorted(mylist)
print(mylist)
mslist = sorted(mylist, key=lambda x: (x[1]), reverse=True)
print(mslist)
from collections import OrderedDict
final = OrderedDict(mslist)
for key, value in final.items():
    print(f'  {key:10} : {value}')

創建以下 output:

[('Romance', '2'), ('Adventure', '1'), ('Action', '3'), ('Horror', '2'), ('History', '2'), ('Comedy', '2')]

[('Action', '3'), ('Adventure', '1'), ('Comedy', '2'), ('History', '2'), ('Horror', '2'), ('Romance', '2')]
[('Action', '3'), ('Comedy', '2'), ('History', '2'), ('Horror', '2'), ('Romance', '2'), ('Adventure', '1')]
  Action     : 3
  Comedy     : 2
  History    : 2
  Horror     : 2
  Romance    : 2
  Adventure  : 1

展示了我在這里所說的內容。

從:

[('Action', '3'), ('Adventure', '1'), ('Comedy', '2'), ('History', '2'), ('Horror', '2'), ('Romance', '2')]
[('Action', '3'), ('Comedy', '2'), ('History', '2'), ('Horror', '2'), ('Romance', '2'), ('Adventure', '1')]

可以看出,第二個排序僅移動'('Adventure', '1')'保持所有其他項目的順序。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM