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”找到第一个,这样就得到了您的结果。