python - 在列表字典中找到最大列表范围的更好(更整洁)的方法是什么
问题描述
我有包含列表作为值的字典。Listlen(2)
表示数组的范围:
new_dict = {0: [0, 7], 1:[15, 21], 2:[-5, 3]}
我需要找到具有最大范围的列表的键,即最大list[1] - list[0]
我已经这样做了,它工作正常,但我假设它可以以更简单或更pythonic的方式完成。
largest = float("-inf")
largest_list = []
for key in new_dict.keys():
temp = new_dict[key][1] - new_dict[key][0]
if temp > largest:
largest = temp
largest_list = new_dict[key]
解决方案
您可以使用max()
自定义key
函数:
>>> new_dict = {0: [0, 7], 1:[15, 21], 2:[-5, 3]}
>>> max(new_dict.items(), key=lambda x: x[1][1] - x[1][0])[0]
2
推荐阅读
- javascript - PostgreSQL 未连接
- r - RStudio 不断将 `/usr/local/bin` 添加到 PATH 变量的前面
- javascript - 如何使用 MongoDB 查询获取每个月的注册用户数?
- powershell - 无法在 powershell 中运行 powershell 脚本
- docker - 为什么入口总是只向特定的服务节点端口返回 502 错误?
- laravel - 在没有模型的数据库中创建查询。拉拉维尔 8
- javascript - 如何验证字符串是否包含 validator.js 中的数字?
- multithreading - 以编程方式停止 tensorflow 训练过程
- php - 如何在谷歌柱形图的列周围添加笔划?
- eclipse - Eclipse 4.18.0 无法打开市场 - NullPointerException