Python - 提取值总和大于 K 的字典
给定一个字典列表,提取所有键总和超过 K 的字典。
Input : test_list = [{“Gfg” : 4, “is” : 8, “best” : 9}, {“Gfg” : 3, “is”: 7, “best” : 5}], K = 15
Output : [{‘Gfg’: 4, ‘is’: 8, ‘best’: 9}]
Explanation : 4 + 9 + 8 = 21. Greater than K, hence returned.
Input : test_list = [{“Gfg” : 4, “is” : 8, “best” : 9}, {“Gfg” : 3, “is”: 7, “best” : 5}], K = 25
Output : []
Explanation : No dictionary with sum > 25.
方法#1:使用循环
这是执行此任务的蛮力方式。在这里,我们迭代所有字典并提取每个字典的总和,如果超过 K,我们将它们过滤掉。
Python3
# Python3 code to demonstrate working of
# Extract dictionaries with values sum greater than K
# Using
# initializing lists
test_list = [{"Gfg" : 4, "is" : 8, "best" : 9},
{"Gfg" : 5, "is": 8, "best" : 1},
{"Gfg" : 3, "is": 7, "best" : 6},
{"Gfg" : 3, "is": 7, "best" : 5}]
# printing original list
print("The original list : " + str(test_list))
# initializing K
K = 15
# using loop to extract all dictionaries
res = []
for sub in test_list:
sum = 0
for key in sub:
sum += sub[key]
if sum > K:
res.append(sub)
# printing result
print("Dictionaries with summation greater than K : " + str(res))
Python3
# Python3 code to demonstrate working of
# Extract dictionaries with values sum greater than K
# Using list comprehension + sum()
# initializing lists
test_list = [{"Gfg" : 4, "is" : 8, "best" : 9},
{"Gfg" : 5, "is": 8, "best" : 1},
{"Gfg" : 3, "is": 7, "best" : 6},
{"Gfg" : 3, "is": 7, "best" : 5}]
# printing original list
print("The original list : " + str(test_list))
# initializing K
K = 15
# using one-liner to extract all the dictionaries
res = [sub for sub in test_list if sum(list(sub.values())) > K]
# printing result
print("Dictionaries with summation greater than K : " + str(res))
输出
The original list : [{'Gfg': 4, 'is': 8, 'best': 9}, {'Gfg': 5, 'is': 8, 'best': 1}, {'Gfg': 3, 'is': 7, 'best': 6}, {'Gfg': 3, 'is': 7, 'best': 5}]
Dictionaries with summation greater than K : [{'Gfg': 4, 'is': 8, 'best': 9}, {'Gfg': 3, 'is': 7, 'best': 6}]
方法 #2:使用列表理解 + sum()
这是可以执行此任务的一种线性方式。在这里,我们使用 sum() 执行求和任务,列表理解可用于执行将所有逻辑组合成一行的任务。
蟒蛇3
# Python3 code to demonstrate working of
# Extract dictionaries with values sum greater than K
# Using list comprehension + sum()
# initializing lists
test_list = [{"Gfg" : 4, "is" : 8, "best" : 9},
{"Gfg" : 5, "is": 8, "best" : 1},
{"Gfg" : 3, "is": 7, "best" : 6},
{"Gfg" : 3, "is": 7, "best" : 5}]
# printing original list
print("The original list : " + str(test_list))
# initializing K
K = 15
# using one-liner to extract all the dictionaries
res = [sub for sub in test_list if sum(list(sub.values())) > K]
# printing result
print("Dictionaries with summation greater than K : " + str(res))
输出
The original list : [{'Gfg': 4, 'is': 8, 'best': 9}, {'Gfg': 5, 'is': 8, 'best': 1}, {'Gfg': 3, 'is': 7, 'best': 6}, {'Gfg': 3, 'is': 7, 'best': 5}]
Dictionaries with summation greater than K : [{'Gfg': 4, 'is': 8, 'best': 9}, {'Gfg': 3, 'is': 7, 'best': 6}]