Python从JSON列表中选择最佳4
我有一个排序的JSON列表,如下所示:Python从JSON列表中选择最佳4,python,json,sorting,Python,Json,Sorting,我有一个排序的JSON列表,如下所示: [{ "id": "1", "score": "5" }, { "id": "1", "score": "4" }, { "id": "2", "score": "9" }, { "id": "2", "score": "8" }, { "id": "3", "score": "99" }, { "id": "3", "score": "98" }] 它按id排序,并根据id对分数进行排序。现在,我想选择每个id最好的4个分数,并将它们存储到一个新列表
[{ "id": "1", "score": "5" },
{ "id": "1", "score": "4" },
{ "id": "2", "score": "9" },
{ "id": "2", "score": "8" },
{ "id": "3", "score": "99" },
{ "id": "3", "score": "98" }]
它按id排序,并根据id对分数进行排序。现在,我想选择每个id最好的4个分数,并将它们存储到一个新列表中。id的分数可能超过4分,也可能不超过4分。排序时间应该是O(n),知道吗?根据
id
和score
对列表进行排序,其中0(n)
采用id
属性,该属性也采用0(n)
因为它已经按分数排序了,只需对它进行迭代,并为每个id获得最好的四个,就完成了,时间复杂度为
O(n)
以下是方法:
import itertools
new_lst = []
for _, g in itertools.groupby(lst, key=lambda x: x['id']):
new_lst.extend(sorted(g, key=lambda x: x['score'], reverse=True)[:4])
不是真正的测试:
>>> lst = [{ "id": "1", "score": "5" },
{ "id": "1", "score": "4" },
{ "id": "2", "score": "9" },
{ "id": "2", "score": "8" },
{ "id": "3", "score": "99" },
{ "id": "3", "score": "98" }]
>>> new_lst = []
>>> for _, g in itertools.groupby(lst, key=lambda x: x['id']):
new_lst.extend(sorted(g, key=lambda x: x['score'], reverse=True)[:4])
>>> new_lst
[{'id': '1', 'score': '5'}, {'id': '1', 'score': '4'}, {'id': '2', 'score': '9'}, {'id': '2', 'score': '8'}, {'id': '3', 'score': '99'}, {'id': '3', 'score': '98'}]
>>> lst = [{ "id": "1", "score": "5" },
{ "id": "1", "score": "4" },
{ "id": "2", "score": "9" },
{ "id": "2", "score": "8" },
{ "id": "3", "score": "99" },
{ "id": "3", "score": "98" }]
>>> new_lst = []
>>> for _, g in itertools.groupby(lst, key=lambda x: x['id']):
new_lst.extend(sorted(g, key=lambda x: x['score'], reverse=True)[:4])
>>> new_lst
[{'id': '1', 'score': '5'}, {'id': '1', 'score': '4'}, {'id': '2', 'score': '9'}, {'id': '2', 'score': '8'}, {'id': '3', 'score': '99'}, {'id': '3', 'score': '98'}]