我有一个字典列表。我希望每个唯一的 api 只有一个结果,并且结果需要根据优先级显示:0、1、2。我可以知道我应该如何处理它吗?
数据:
[
{'api':'test1', 'result': 0},
{'api':'test2', 'result': 1},
{'api':'test3', 'result': 2},
{'api':'test3', 'result': 0},
{'api':'test3', 'result': 1},
]
预期输出:[
{'api':'test1', 'result': 0},
{'api':'test2', 'result': 1},
{'api':'test3', 'result': 0},
]
最佳答案
假设输入 data
你可以做经典的 sql-ish groupby
:
from itertools import groupby
# in case your data is sorted already by api skip the below line
data = sorted(data, key=lambda x: x['api'])
res = [
{'api': g, 'result': min(v, key=lambda x: x['result'])['result']}
for g, v in groupby(data, lambda x: x['api'])
]
输出:[{'api': 'test1', 'result': 0}, {'api': 'test2', 'result': 1}, {'api': 'test3', 'result': 0}]
关于python - 如何从列表中检索最小唯一值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65518787/