首页 > 解决方案 > 从列表中获取最大值的子列表

问题描述

我正在尝试检索列表中具有最大键值的子列表。

例如。在此示例中,我试图检索具有最大置信度分数的子列表:

 listA=[{'id': '1', 'actions': [{'acc': 'ac1', 'coordinates': [569, 617, 627, 631], 'confidence': 93.0}]}, {'id': '1', 'actions': [{'acc': 'acc1','coordinates': [569, 617, 627, 631], 'confidence': 94.0}]}, {'id': '1', 'actions': [{'acc': 'acc1', 'coordinates': [569, 617, 627, 631], 'confidence': 95.0}]}]

预期的输出是:

[{'id': '1', 'actions': [{'acc': 'acc1', 'coordinates': [569, 617, 627, 631], 'confidence': 95.0}]

我使用了 itemgetter,但它没有返回所需的输出。

标签: pythonlistmaxsublist

解决方案


我使用了 python 的 max 函数并为其提供了一个键,该键将使用置信度键值作为查找最大值的方法。

listA=[{'id': '1', 'actions': [{'acc': 'ac1', 'coordinates': [569, 617, 627, 631], 'confidence': 93.0}]},
       {'id': '1', 'actions': [{'acc': 'acc1','coordinates': [569, 617, 627, 631], 'confidence': 94.0}]},
       {'id': '1', 'actions': [{'acc': 'acc1', 'coordinates': [569, 617, 627, 631], 'confidence': 95.0}]}]

maxList = max(listA, key=lambda x: x['actions'][0]['confidence'])
print(maxList)

如果您想返回项目的排序列表而不仅仅是最大值,您可以做几乎完全相同的事情。你只需替换maxsorted

编辑:感谢@tobias_k 的好建议。如果有多个操作,请将 lambda 替换为lambda x: max(a['confidence'] for a in x['actions'])


推荐阅读