Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 查找某个键的最大值_Python_Dictionary_Max - Fatal编程技术网

Python 查找某个键的最大值

Python 查找某个键的最大值,python,dictionary,max,Python,Dictionary,Max,我需要“cost”的最大值,如果有两个或多个相同键的最大值相同,那么我需要将它们全部放入一个列表中 例如: 我需要输出如下所示: 我们如何做到这一点 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 = [

我需要“cost”的最大值,如果有两个或多个相同键的最大值相同,那么我需要将它们全部放入一个列表中

例如:

我需要输出如下所示:

我们如何做到这一点

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)
首先,浏览字典列表,获取所有费用并将其添加到列表中。接下来,在列表中找到最大值。然后,再次浏览字典列表,并将每个字典的成本等于max val附加到结果列表中。然后打印结果列表


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

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

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

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

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

我想做一些像maxfruits这样的事情,key=lambda x:x['cost'],但这只返回第一个max项。有解决办法吗?我想做一些像maxfruits这样的事情,key=lambda x:x['cost'],但这只返回第一个max项。有解决方法吗?尝试了@jpp-answer,它对我非常有效。尝试了@jpp-answer,它对我非常有效。
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}]