【问题标题】:Python sort a JSON list by two key valuesPython 按两个键值对 JSON 列表进行排序
【发布时间】:2015-04-14 00:06:22
【问题描述】:

我的 JSON 列表如下所示:

[{ "id": "1", "score": "100" },
{ "id": "3", "score": "89" },
{ "id": "1", "score": "99" },
{ "id": "2", "score": "100" },
{ "id": "2", "score": "59" }, 
{ "id": "3", "score": "22" }]

我想先对id排序,我用过

sorted_list = sorted(json_list, key=lambda k: int(k['id']), reverse = False)

这只会按id对列表进行排序,但是根据id,我也想对分数进行排序,我想要的最终列表是这样的:

[{ "id": "1", "score": "100" },
{ "id": "1", "score": "99" },
{ "id": "2", "score": "100" },
{ "id": "2", "score": "59" },
{ "id": "3", "score": "89" }, 
{ "id": "3", "score": "22" }]

因此,对于每个 id,也要对其分数进行排序。知道该怎么做吗?

【问题讨论】:

    标签: python json sorting


    【解决方案1】:

    使用添加第二个排序键-int(k["score"]) 的元组在打破平局时反转顺序并删除reverse=True

    sorted_list = sorted(json_list, key=lambda k: (int(k['id']),-int(k["score"])))
    
    [{'score': '100', 'id': '1'}, 
     {'score': '99', 'id': '1'}, 
     {'score': '100', 'id': '2'}, 
     {'score': '59', 'id': '2'},
     {'score': '89', 'id': '3'}, 
     {'score': '22', 'id': '3'}]
    

    所以我们主要按id 从最低到最高排序,但我们使用score 从最高到最低来打破平局。 dicts 也是无序的,所以当你打印时,如果不使用 OrderedDict,就无法将 id 放在 score 之前。

    或者使用 pprint:

    from pprint import pprint as pp
    
    pp(sorted_list)
    
    [{'id': '1', 'score': '100'},
     {'id': '1', 'score': '99'},
     {'id': '2', 'score': '100'},
     {'id': '2', 'score': '59'},
     {'id': '3', 'score': '89'},
     {'id': '3', 'score': '22'}]
    

    【讨论】:

    • @MalikBrahimi,我不认为你会得到正确的输出,OP 想要从最低到最高的 id 排序,但打破从最高到最低分数的关系
    • @MalikBrahimi,我应该是 x,但它仍然无法正常工作,如果不强制转换为 int,您将无法对字符串数字进行排序,在这种情况下,OP 希望以两种方式进行排序,因此它不是一个简单的排序跨度>
    • 好答案。您可以在分数之前打印出 id,而无需为排序列表中的每个字典使用 OrderedDict'{{ "id": "{id}", "score": "{score}" }}'.format(**dct) 之类的东西。
    • 谢谢@PadraicCunningham,你太棒了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-09
    • 1970-01-01
    • 2012-11-20
    • 2020-10-04
    相关资源
    最近更新 更多