📜  显示最大范围列表值键的Python程序

📅  最后修改于: 2022-05-13 01:55:23.039000             🧑  作者: Mango

显示最大范围列表值键的Python程序

给定一个包含列表的键和值的字典,以下程序显示其范围最大的值的键。

Range = Maximum number-Minimum number

方法一: 使用max() , min()循环

在这里,我们获取每个列表的 max() 和 min() 并执行差异以找到范围。然后存储该值,并通过在结果列表中应用 max() 来计算所有这些值的最大差值。

Python3
# initializing dictionary
test_dict = {"Gfg" : [6, 2, 4, 1], "is" : [4, 7, 3, 3, 8], "Best" : [1, 0, 9, 3]}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
max_res = 0
for sub, vals in test_dict.items():
      
    # storing maximum of difference
    max_res = max(max_res, max(vals) - min(vals))    
    if max_res == max(vals) - min(vals):
        res = sub
          
# printing result 
print("The maximum element key : " + str(res))


Python3
# initializing dictionary
test_dict = {"Gfg" : [6, 2, 4, 1], "is" : [4, 7, 3, 3, 8], "Best" : [1, 0, 9, 3]}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# getting max value 
max_res = max([max(vals) - min(vals) for sub, vals in test_dict.items()])
  
# getting key matching with maximum value 
res = [sub for sub in test_dict if max(test_dict[sub]) - min(test_dict[sub]) == max_res][0]
  
# printing result 
print("The maximum element key : " + str(res))


输出:

方法 2:使用列表推导 max()min()

在这里,我们计算最大范围,然后使用列表理解提取与该差异匹配的键。

蟒蛇3

# initializing dictionary
test_dict = {"Gfg" : [6, 2, 4, 1], "is" : [4, 7, 3, 3, 8], "Best" : [1, 0, 9, 3]}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# getting max value 
max_res = max([max(vals) - min(vals) for sub, vals in test_dict.items()])
  
# getting key matching with maximum value 
res = [sub for sub in test_dict if max(test_dict[sub]) - min(test_dict[sub]) == max_res][0]
  
# printing result 
print("The maximum element key : " + str(res)) 

输出: