显示最大范围列表值键的Python程序
给定一个包含列表的键和值的字典,以下程序显示其范围最大的值的键。
Range = Maximum number-Minimum number
Input : test_dict = {“Gfg” : [6, 2, 4, 1], “is” : [4, 7, 3, 3, 8], “Best” : [1, 0, 9, 3]}
Output : Best
Explanation : 9 – 0 = 9, Maximum range compared to all other list given as values
Input : test_dict = {“Gfg” : [16, 2, 4, 1], “Best” : [1, 0, 9, 3]}
Output : Gfg
Explanation : 16 – 1 = 15, Maximum range compared to all other list given as values
方法一: 使用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))
输出:
The original dictionary is : {‘Gfg’: [6, 2, 4, 1], ‘is’: [4, 7, 3, 3, 8], ‘Best’: [1, 0, 9, 3]}
The maximum element key : Best
方法 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))
输出:
The original dictionary is : {‘Gfg’: [6, 2, 4, 1], ‘is’: [4, 7, 3, 3, 8], ‘Best’: [1, 0, 9, 3]}
The maximum element key : Best