Skip to main content
 首页 » 编程设计

python之查找某个键的最大值

2025年05月04日21thcjp

我需要 '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}] 

我们如何做到这一点?

请您参考如下方法:

计算最大成本,然后使用列表理解:

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}]