如何解决从列表中获取最大值的子列表
我正在尝试检索列表中具有最大键值的子列表。
例如在此示例中,我试图检索具有最大置信度得分的子列表:
listA=[{'id': '1','actions': [{'acc': 'ac1','coordinates': [569,617,627,631],'confidence': 93.0}]},{'id': '1','actions': [{'acc': 'acc1','confidence': 94.0}]},'confidence': 95.0}]}]
预期输出为:
[{'id': '1','confidence': 95.0}]
我使用了itemgetter,但未返回所需的输出。
解决方法
我使用了python的max函数,并为其提供了一个密钥,该密钥将使用置信度键值作为查找最大值的方法。
listA=[{'id': '1','actions': [{'acc': 'ac1','coordinates': [569,617,627,631],'confidence': 93.0}]},{'id': '1','actions': [{'acc': 'acc1','confidence': 94.0}]},'confidence': 95.0}]}]
maxList = max(listA,key=lambda x: x['actions'][0]['confidence'])
print(maxList)
如果您想返回项目的排序列表,而不仅仅是返回最大值,则可以执行几乎完全相同的操作。您只需将max
替换为sorted
编辑:感谢@tobias_k的好建议。如果有多个动作,请用lambda x: max(a['confidence'] for a in x['actions'])
这是一个可能的解决方案,您会发现lambda难以理解。
我将其设置为非常冗长且对新手友好,因此新手也可以使用它:
listA=[{'id': '1','confidence': 95.0}]}]
max_confidence_item = None
max_confidence_value = float('-inf') # This is just a VERY small number so that we are sure that every confidence we find as first is bigger than this number
for item in listA:
current_confidence_value = item['actions'][0]['confidence']
current_confidence_item = item
if (max_confidence_value < current_confidence_value):
max_confidence_value = current_confidence_value
max_confidence_item = current_confidence_item
print(max_confidence_item)
输出
{'id': '1','actions': [{'confidence': 95.0,'acc': 'acc1'}]}
,
confidence = 0
i = 0
for _ in range(len(listA)):
if confidence < listA[_]['actions'][0]['confidence']:
i += 1
confidence = listA[_]['actions'][0]['confidence']
print(listA[i -1])
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。