python - 在列表字典中查找最大列表范围的更好(更简洁)方法是什么

我有一个由列表作为值组成的字典。列表是 len(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

https://stackoverflow.com/questions/63754663/

相关文章:

r - separate_rows 在结果周围生成引号

c - main的地址是什么?

python - 类型错误 : request() missing 1 required posit

java - 阵列旋转 TLE(超出时间限制)

scala - 如何在不分配给 val 的情况下使用隐式调用返回的函数

python - 如何在 Python 中订阅 NATS 主题并继续接收消息?

python - 从数据框中删除列中以 "@"开头的单词

html - 轮播滑动动画不适用于 Bootstrap 4.5.2

angular - 使用@input 对 Angular 组件进行单元测试

python - Python 中的日期字符串格式化