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