如何从列表中检索最小唯一值?
我有一个字典列表。我希望每个唯一的 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}]
回答
您可以通过一次列表并保留您在每个组中看到的最佳列表。这是时间和空间效率。
def get_min_unique(items, id_key, value_key):
lowest = {}
for item in items:
key = item[id_key]
if key not in lowest or lowest[key][value_key] > item[value_key]:
lowest[key] = item
return list(lowest.values())
例如使用您自己的数据:
data = [
{'api':'test1', 'result': 0},
{'api':'test2', 'result': 1},
{'api':'test3', 'result': 2},
{'api':'test3', 'result': 0},
{'api':'test3', 'result': 1},
]
assert get_min_unique(data, 'api', 'result') == [
{'api': 'test1', 'result': 0},
{'api': 'test2', 'result': 1},
{'api': 'test3', 'result': 0},
]
回答
data = [
{'api': 'test1', 'result': 0},
{'api': 'test3', 'result': 2},
{'api': 'test2', 'result': 1},
{'api': 'test3', 'result': 1},
{'api': 'test3', 'result': 0}
]
def find(data):
step1 = sorted(data, key=lambda k: k['result'])
print('step1', step1)
step2 = {}
for each in step1:
if each['api'] not in step2:
step2[each['api']] = each
print('step2', step2)
step3 = list(step2.values())
print('step3', step3)
print('n')
return step3
find(data)
试试这个,它会给你
step1 [{'api': 'test1', 'result': 0}, {'api': 'test3', 'result': 0}, {'api': 'test2', 'result': 1}, {'api': 'test3', 'result': 1}, {'api': 'test3', 'result': 2}]
step2 {'test1': {'api': 'test1', 'result': 0}, 'test3': {'api': 'test3', 'result': 0}, 'test2': {'api': 'test2', 'result': 1}}
step3 [{'api': 'test1', 'result': 0}, {'api': 'test3', 'result': 0}, {'api': 'test2', 'result': 1}]
首先对所有内容进行排序,然后为每个“api”查找第一个,结果就出来了。
- You kind of reinvented the wheel - see `itertools.groupby` - it does literally the same as your function