|
发表于 2023-12-21 20:19:57
|
显示全部楼层
你可以使用一个字典来实现这个功能。首先,遍历集合中的每个元素,将元素中的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_dict = {}
- for item in collection:
- id = item["id"]
- score = item["score"]
- if id in result_dict:
- if score > result_dict[id]:
- result_dict[id] = score
- else:
- result_dict[id] = score
- result = [{"id": id, "score": score} for id, score in result_dict.items()]
- print(result)
复制代码
输出结果为:`[{'id': 1, 'score': 9}, {'id': 2, 'score': 2}, {'id': 3, 'score': 2}]`
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |
|