[英]Sort by values (descending) and then keys (ascending) in Python dictionary
[英]Sort a dictionary by values in ascending order and by keys in descending order
我正在尝试对字典进行排序,我要遵循的顺序是首先,字典应该按值按升序排序,如果两个或多个键的值相等,那么我想按键对字典进行排序按降序排列。
这是代码:
dictionary = {0: 150, 1: 151, 2: 150, 3: 101, 4: 107}
print(sorted(dictionary.items(), key=lambda x: (x[1], x[0])))
我希望 output 为以下内容: [(3, 101), (4, 107), (2, 150), (0, 150), (1, 151)]
但是 output 是: [(3, 101), (4, 107), (0, 150), (2, 150), (1, 151)]
因为这里的值是数字的,所以你可以使用否定作为与反转排序顺序相同的效果:
sorted(dictionary.items(), key=lambda x: (x[1], -x[0]))
对于不能依赖数值的更通用的情况,这里是一种可能的方法,尽管可能有更好的方法。
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)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.