【问题标题】:Sort a dictionary by values in ascending order and by keys in descending order按值升序和键降序对字典进行排序
【发布时间】:2020-12-10 13:11:52
【问题描述】:

我正在尝试对字典进行排序,我要遵循的顺序是首先,字典应该按值按升序排序,如果两个或多个键的值相等,那么我想对字典进行排序按降序排列。

代码如下:

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)]

【问题讨论】:

  • 鉴于值是数字,您可以使用sorted(dictionary.items(), key=lambda x: (-x[1], x[0]))
  • 如果您希望两个值同时按相反方向排序,您必须将其中一个设为
  • @jonrsharpe 如果两者都不是数字,有什么通用建议吗? (我之前能想到的只是按照cmp1 or cmp2 的行编写一个组合的cmp 函数并使用cmp_to_key。)
  • 我在上面写的与所要求的相反(尽管一般原则成立)-在下面的回答中更正。
  • 这里,您使用的是 sorted(),它以升序为默认值

标签: python dictionary data-structures


【解决方案1】:

因为这里的值是数字,您可以使用否定作为反转排序顺序的效果:

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)))

【讨论】:

  • 如果有人有更好的方法来处理通用案例,请您发布答案(并让我知道)。
  • 这个问题不值得点赞吗?
  • (上面已经回复了)
猜你喜欢
  • 1970-01-01
  • 2021-12-20
  • 2011-07-08
  • 2013-08-15
  • 2021-05-19
  • 1970-01-01
  • 2016-10-18
  • 1970-01-01
相关资源
最近更新 更多