Python通过两个键值对JSON列表进行排序 [英] Python sort a JSON list by two key values
问题描述
我有一个JSON列表,如下所示:
I have a JSON list looks like this:
[{ "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进行排序,我用过
I want to sort the id first, I used
sorted_list = sorted(json_list, key=lambda k: int(k['id']), reverse = False)
这只会按ID对列表进行排序,但基于ID,我也想对分数进行排序,我想要的最终列表是这样的:
This will only sort the list by id, but base on id, I also want sort the score as will, the final list I want is like this:
[{ "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,也要对其得分进行排序.知道怎么做吗?
So for each id, sort their score as well. Any idea how to do that?
推荐答案
使用元组添加第二个排序键-int(k["score"])
来打破平局时的顺序并删除reverse=True
:
use a tuple adding second sort key -int(k["score"])
to reverse the order when breaking ties and remove 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
从最高到最低的顺序来打破平局.字典也是无序的,因此在打印时如果不使用OrderedDict,就无法将id放在得分之前.
So we primarily sort by id
from lowest-highest but we break ties using score
from highest-lowest. dicts are also unordered so there is no way to put id before score when you print without maybe using an OrderedDict.
或使用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'}]
这篇关于Python通过两个键值对JSON列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!