首页 > 解决方案 > 在列表字典中找到最大列表范围的更好(更整洁)的方法是什么

问题描述

我有包含列表作为值的字典。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]

标签: pythonlistdictionary

解决方案


您可以使用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

推荐阅读