gpt4 book ai didi

python - 在字典列表中查找最大值

转载 作者:行者123 更新时间:2023-11-28 20:50:04 24 4
gpt4 key购买 nike

给定一个数据结构:

   [
{'id':0, 'items':
[
{'id': 0, name: "Tom1", age: 10},
{'id': 0, name: "Mark1", age: 15},
{'id': 0, name: "Pam1", age: 17}
]
},
{'id':1, 'items':
[
{'id': 1, name: "Tom12", age: 8},
{'id': 1, name: "Mark12", age: 3},
{'id': 1, name: "Pam12", age: 2}
]
},

{'id':2, 'items':
[
{'id': 2, name: "Tom13", age: 55},
{'id': 2, name: "Mark13", age: 66},
{'id': 2, name: "Pam13", age: 77}
]
},
]

我想在每个字典中找到一个年龄具有最大值的项目并选择它。我该如何实现?

最佳答案

试试这个:

for dVals in yourData:
print max(dVals['items'], key=lambda x:x['age'])

或单行:

print [max(dVals['items'], key=lambda x: x['age']) for dVals in yourData]

{'id': 0, 'age': 17, 'name': 'Pam1'}
{'id': 1, 'age': 8, 'name': 'Tom12'}
{'id': 2, 'age': 77, 'name': 'Pam13'}

关于python - 在字典列表中查找最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13262382/

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