查找某个键的最大值

2024-09-23 04:21:11 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我们怎么做


Tags: id列表resultmaxcostfruitsorangesapples
2条回答

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

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

首先,浏览字典列表,获取所有成本并将其添加到列表中。接下来,在列表中找到最大值。然后,再次遍历dictionary列表,并将每个dictionary的开销等于max val添加到结果列表中。然后打印结果列表

相关问题 更多 >