gpt4 book ai didi

python - 查找某个键的最大值

转载 作者:太空宇宙 更新时间:2023-11-04 08:32:57 25 4
gpt4 key购买 nike

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

关于python - 查找某个键的最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51429969/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com