为什么这个答案已经有其他三个?
在我看来,其他答案都没有揭示问题中描述的问题的核心,顺便说一下,已经充分回答了here: https://stackoverflow.com/questions/20145842/python-sorting-by-multiple-criteria和here 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 的排序算法是稳定的,这意味着相等的元素保持它们的相对顺序。因此,您可以对第二个元素使用第一个排序(按升序排序),然后再次排序,仅对第一个元素按相反的顺序排序。
我已将问题中列出的字典更改为仅包含字符串值,这将不允许在键函数中使用带有负数值的“技巧”来获得所需的结果来演示上面所说的内容。
下面的代码:
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}')
创建以下输出:
[('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')',保持所有其他项目的顺序。