python - 如何从列表中检索最小唯一值?

标签 python

我有一个字典列表。我希望每个唯一的 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/

相关文章:

python - 通过 Cython 调用 inet_pton

python - 如何从特定输入中排除输入?

python - 添加要在 tkinter 中显示的变量

python - BeautifulSoup 库的 HTML 解析问题

python - 相当于 python 在 golang 中的编码 ('utf8' )

python - Python 中的 "Bitwise Not"不考虑 2 的补码

jquery - 链接停止工作——jquery 问题?

Python 正则表达式搜索数字范围

python - 如何使用drive-sdk共享文件?

python - Pyinstaller/Django - pkg_resources.DistributionNotFound : The 'django-omnibus' distribution was not found