python - 从列表中获取最大值的子列表
问题描述
我正在尝试检索列表中具有最大键值的子列表。
例如。在此示例中,我试图检索具有最大置信度分数的子列表:
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 函数并为其提供了一个键,该键将使用置信度键值作为查找最大值的方法。
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)
如果您想返回项目的排序列表而不仅仅是最大值,您可以做几乎完全相同的事情。你只需替换max
为sorted
编辑:感谢@tobias_k 的好建议。如果有多个操作,请将 lambda 替换为lambda x: max(a['confidence'] for a in x['actions'])
推荐阅读
- c# - 在调试其他项目时在 C# 中运行 NUnit 测试
- python - 带有 Flask 的 pytest:无需 create_app() 即可轻松引入我们的应用程序设置?
- openlayers - 如何获取 GPX 文件的范围以将其显示在地图上(使用 openalyers)
- java - 在自定义异常类java中处理内部类异常
- python - 使用 Python 在目录中找不到以 .sha1 结尾的文件
- mysql - 基于 Liunx 的 Azure PHP 应用服务缺少 MYSQL 驱动程序
- c++ - 如何根据模板参数包是否与函数参数匹配来控制模板函数定义?
- spring - 如何在JSP中显示第一列中的奇数数据和第二列中的偶数数据?
- google-chrome-devtools - 使用 webpack-dev-server 时,为什么 Chrome 会在每个第二个请求之前等待?
- linux - 在 zsh 中混合进程替换和管道