【问题标题】:Python sorting list of dictionary [duplicate]字典的Python排序列表[重复]
【发布时间】:2021-07-16 03:29:43
【问题描述】:

我有一个字典列表,如下所示,

x = [
   {"matches_count": 10, distance: 50},
   {"matches_count": 20, distance: 50},
   {"matches_count": 1, "distance: 20},
   {"matches_count": 2, "distance": 20},
   {"matches_count": 5, "distance: 30},
]

我需要像下面这样排序

x = [
  {"matches_count": 2, distance: 20},
  {"matches_count": 1, "distance: 20},
  {"matches_count": 5, "distance: 30},
  {"matches_count": 20, distance: 50},
  {"matches_count": 10, "distance": 50} 
]

基本上,这应该使用 distancema​​tches_count 进行排序。当距离相同时,最高匹配数应该排在第一位。有没有可能用 sorted 方法做到这一点?或者有没有其他方法可以做到这一点?

我已经检查了以下问题,但我无法从这些问题中获得正确的见解。 Sort list of dictionaries by multiple keys with different ordering

【问题讨论】:

标签: python


【解决方案1】:

您可以只按一个键排序,其中键是一个元组,然后翻转匹配计数的符号。这将首先按距离升序排序,然后匹配降序。

x.sort(key=lambda e: (e["distance"], -e["matches_count"]))

【讨论】:

    【解决方案2】:

    你可以使用sorted函数:

    print(sorted(x, key=lambda a: (a['distance'], -a['matches_count'])))
    

    输出:

    [{'matches_count': 2, 'distance': 20}, {'matches_count': 1, 'distance': 20}, {'matches_count': 5, 'distance': 30}, {'matches_count': 20, 'distance': 50}, {'matches_count': 10, 'distance': 50}]
    

    首先按distance 键排序,如果相同,则按matches_count 的负数排序。我把它设为负数,所以它按降序而不是升序排序。

    【讨论】:

      【解决方案3】:
      x = [
          {"matches_count": 10, "distance": 50},
          {"matches_count": 20, "distance": 50},
          {"matches_count": 1, "distance": 20},
          {"matches_count": 2, "distance": 20},
          {"matches_count": 5, "distance": 30},
      ]
      
      x.sort(key=lambda k: (k['distance'], -k['matches_count']))
      
      for e in x:
          print(e)
      

      【讨论】:

        猜你喜欢
        • 2021-06-30
        • 1970-01-01
        • 2019-05-14
        • 2018-10-22
        • 1970-01-01
        • 2015-04-01
        • 2020-03-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多