|
发表于 2023-12-21 20:17:55
|
显示全部楼层
要实现这个功能,你可以使用一个字典来存储每个id对应的最高score值。遍历集合中的每个元素,如果该元素的id已经在字典中存在,则比较score大小,更新为较大的值;如果该元素的id还没有在字典中存在,则将该元素的id和score作为键值对添加到字典中。最后,遍历字典,将其中的键值对转换为列表形式,即可得到查询结果。
下面是一个示例代码:
- collection = [{'id': 1, 'score': 9}, {'id': 1, 'score': 2}, {'id': 1, 'score': 3}, {'id': 2, 'score': 2}, {'id': 2, 'score': 1}, {'id': 3, 'score': 2}]
- result = {}
- for item in collection:
- id = item['id']
- score = item['score']
- if id in result:
- if score > result[id]:
- result[id] = score
- else:
- result[id] = score
- query_result = [{'id': k, 'score': v} for k, v in result.items()]
- print(query_result)
复制代码
运行上述代码,输出结果为`[{'id': 1, 'score': 9}, {'id': 2, 'score': 2}, {'id': 3, 'score': 2}]`,与你所期望的查询结果一致。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |
|