📜  Python – 提取总和大于 K 的字典项

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

Python – 提取总和大于 K 的字典项

给定带有值列表的字典,提取所有值总和超过 K 的项目。

方法 #1:使用字典理解 + sum()

这是可以解决此问题的方法之一。在这个单行代码中,我们遍历键并仅在字典项的值的总和超过使用 sum() 计算的 K 时附加字典项。

Python3
# Python3 code to demonstrate working of 
# Extract Dictionary Items with Summation Greater than K
# Using dictionary comprehension + sum()
  
# initializing dictionary
test_dict = {"Gfg" : [6, 3, 4], 
             "is" :  [8, 10, 12], 
             "Best" : [10, 16, 14],  
             "for" : [7, 4, 3], 
             "geeks" : [1, 2, 3, 4]}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# initializing K 
K = 15
  
# summation using sum(), values extracted using items()
res = {key: val for key, val in test_dict.items() if sum(val) > K}
  
# printing result 
print("The computed dictionary : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Extract Dictionary Items with Summation Greater than K
# Using filter() + lambda() + sum() + dict()
  
# initializing dictionary
test_dict = {"Gfg" : [6, 3, 4], 
             "is" :  [8, 10, 12], 
             "Best" : [10, 16, 14],  
             "for" : [7, 4, 3], 
             "geeks" : [1, 2, 3, 4]}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# initializing K 
K = 15
  
# summation using sum(), values extracted using items()
# filter() + lambda used for computation
res = dict(filter(lambda ele: sum(ele[1]) > K, test_dict.items()))
  
# printing result 
print("The computed dictionary : " + str(res))


输出
The original dictionary is : {'Gfg': [6, 3, 4], 'is': [8, 10, 12], 'Best': [10, 16, 14], 'for': [7, 4, 3], 'geeks': [1, 2, 3, 4]}
The computed dictionary : {'is': [8, 10, 12], 'Best': [10, 16, 14]}

方法 #2:使用 filter() + lambda() + sum() + dict()

这是可以执行此任务的另一种方式。在此,计算部分使用 filter() 和 lambda 完成,使用 sum() 求和,使用 dict() 将结果转换为字典。

Python3

# Python3 code to demonstrate working of 
# Extract Dictionary Items with Summation Greater than K
# Using filter() + lambda() + sum() + dict()
  
# initializing dictionary
test_dict = {"Gfg" : [6, 3, 4], 
             "is" :  [8, 10, 12], 
             "Best" : [10, 16, 14],  
             "for" : [7, 4, 3], 
             "geeks" : [1, 2, 3, 4]}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# initializing K 
K = 15
  
# summation using sum(), values extracted using items()
# filter() + lambda used for computation
res = dict(filter(lambda ele: sum(ele[1]) > K, test_dict.items()))
  
# printing result 
print("The computed dictionary : " + str(res)) 
输出
The original dictionary is : {'Gfg': [6, 3, 4], 'is': [8, 10, 12], 'Best': [10, 16, 14], 'for': [7, 4, 3], 'geeks': [1, 2, 3, 4]}
The computed dictionary : {'is': [8, 10, 12], 'Best': [10, 16, 14]}