从列表中获取具有最大值的子列表

Get the sublist with a maximum value from a list

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

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

 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,但它没有返回所需的输出。

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

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)

如果您想要 return 项目的排序列表而不仅仅是最大值,您可以做几乎完全相同的事情。您只需将 max 替换为 sorted

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

如果您觉得 lambda 难以理解,这里有一个可能的解决方案。

我把它写得非常冗长并且对初学者友好,所以它也可以被新手使用:

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

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, 'coordinates': [569, 617, 627, 631], '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])