我需要'cost'的最大值,如果同一键有两次或多次出现且值(max)相同,那么我需要将所有这些都放在一个列表中。
例如:
fruits = [{'nama':'oranges','id':9635,'cost':23}, {'nama':'lemons','id':946,'cost':17}, {'nama':'apples','id':954,'cost':16}, {'nama':'oranges','id':989,'cost':23}]
我需要输出像这样:
result = [{'nama':'oranges','id':9635,'cost':23}, {'nama':'oranges','id':989,'cost':23}]
我们如何做到这一点?
答案 0 :(得分:3)
计算最高费用,然后使用列表理解:
from operator import itemgetter
max_cost = max(map(itemgetter('cost'), fruits))
# or max_cost = max(i['cost'] for i in fruits)
res = [i for i in fruits if i['cost'] == max_cost]
print(res)
[{'nama': 'oranges', 'id': 9635, 'cost': 23},
{'nama': 'oranges', 'id': 989, 'cost': 23}]
答案 1 :(得分:2)
fruits = [{'nama':'oranges','id':9635,'cost':23}, {'nama':'lemons','id':946,'cost':17}, {'nama':'apples','id':954,'cost':16}, {'nama':'oranges','id':989,'cost':23}]
costs = []
for i in fruits:
costs.append(i['cost'])
max_val = max(costs)
result = []
for i in fruits:
if i['cost'] == max_val:
result.append(i)
print(result)
首先,浏览字典列表,获取所有成本并将其附加到列表中。接下来,在列表中找到最大值。然后,再次浏览字典列表,并将每个字典的成本等于最大值附加到结果列表中。然后打印结果列表。