【问题标题】:Python sorting json list by 2 key values of different typesPython按2个不同类型的键值对json列表进行排序
【发布时间】:2020-12-18 03:13:34
【问题描述】:

我一直在关注这个答案: Python sort a JSON list by two key values

我想根据我的情况进行调整:

[
    {'score': 0.1, 'id': 1, 'flag': true}, 
    {'score': 0.234, 'id': 2, 'flag': false}, 
    {'score': 0.4, 'id': 3, 'flag': false}
]

我需要按标志(布尔)和分数(浮点)进行排序,就像您在 SQL 中所做的那样。 在这种情况下,结果将是:

[
    {'score': 0.1, 'id': 1, 'flag': true}, // first because the flag is true
    {'score': 0.4, 'id': 3, 'flag': false} //second because the score is higher 
    {'score': 0.234, 'id': 2, 'flag': false}, 

]

我正在尝试使用

sorted_result = sorted(json, key=lambda k: (bool(k['flag']), -float(k['score'])))

但它没有按预期排序

【问题讨论】:

  • 您提到的问题似乎为您提供了所需的所有信息。但是为了完整起见,您应该使用代码产生的实际输出来更新您的问题,
  • 好吧,它不包括 bool 和 float 标志的组合。排序结果不存在!
  • 您需要提供两个排序键,即flag, score
  • 这和 JSON 有什么关系?

标签: python json


【解决方案1】:

也可以否定flag:

>>> data = [{'score': 0.1, 'id': 1, 'flag': True}, 
            {'score': 0.234, 'id': 2, 'flag': False}, 
            {'score': 0.4, 'id': 3, 'flag': False}]

>>> sorted(data, key = lambda k: (-k['flag'], -k['score']))
[{'score': 0.1, 'id': 1, 'flag': True}, {'score': 0.4, 'id': 3, 'flag': False}, {'score': 0.234, 'id': 2, 'flag': False}]

你也不需要在这里输入bool() 和float(),因为类型已经被推断出来了。

【讨论】:

    【解决方案2】:

    您可以使用返回元组作为排序键的 lambda 函数。您也可以使用reverse=True 代替否定值来按降序排序:True 在 False 之前,值从大到小。

    j = [
        {'score': 0.1, 'id': 1, 'flag': True},
        {'score': 0.234, 'id': 2, 'flag': False},
        {'score': 0.4, 'id': 3, 'flag': False}
    ]
    
    sorted(j, key=lambda x: (x.get('flag'), x.get('score')), reverse=True)
    # returns:
    [{'flag': True, 'id': 1, 'score': 0.1},
     {'flag': False, 'id': 3, 'score': 0.4},
     {'flag': False, 'id': 2, 'score': 0.234}]
    

    如果您从字符串加载 json,请使用:

    import json
    j = json.loads('''[
        {"score": 0.1, "id": 1, "flag": true}, 
        {"score": 0.234, "id": 2, "flag": false}, 
        {"score": 0.4, "id": 3, "flag": false}
    ]''')
    

    【讨论】:

    • 是的,这是另一种方法。我觉得这比携带否定更干净。
    【解决方案3】:

    如果您尝试对 int/float 的一个值进行升序排序,并且如果存在平局,请对另一个字符串值进行升序排序,这里是 :D:

    arr = [{'score': 10, 'name': 'Helen'},{'score': 10, 'name': 'Zed'},{'score': 10, 'name': 'Bob'}, {'score': 15, 'name':'Susan'}, {'score': 1, 'name': 'Skippy'}]
    arr
    
    [{'score': 10, 'name': 'Helen'},
     {'score': 10, 'name': 'Zed'},
     {'score': 10, 'name': 'Bob'},
     {'score': 15, 'name': 'Susan'},
     {'score': 1, 'name': 'Skippy'}]
    
    sorted(arr, key = lambda k: (k['score'], k['name']))
    
    [{'score': 1, 'name': 'Skippy'},
     {'score': 10, 'name': 'Bob'},
     {'score': 10, 'name': 'Helen'},
     {'score': 10, 'name': 'Zed'},
     {'score': 15, 'name': 'Susan'}]  
    

    【讨论】:

      猜你喜欢
      • 2015-04-14
      • 2023-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-02
      • 2023-01-22
      相关资源
      最近更新 更多