Python – 关键列表汇总
有时,在使用Python字典时,我们可能会遇到问题,我们需要使用值中所有键的总和来执行键替换。这可以应用于包括数据计算在内的许多领域,例如机器学习。让我们讨论可以执行此任务的某些方式。
方法 #1:使用sum()
+ 循环
这是可以执行此任务的方式之一。在此,我们使用 sum 执行求和,并使用循环以暴力方式完成对每个键的迭代。
# Python3 code to demonstrate working of
# Key Values Summations
# Using sum() + loop
# initializing dictionary
test_dict = {'gfg' : [4, 6, 8], 'is' : [9, 8, 2], 'best' : [10, 3, 2]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Key Values Summations
# Using sum() + loop
for key, value in test_dict.items():
test_dict[key] = sum(value)
# printing result
print("The summation keys are : " + str(test_dict))
输出 :
The original dictionary is : {‘gfg’: [4, 6, 8], ‘is’: [9, 8, 2], ‘best’: [10, 3, 2]}
The summation keys are : {‘gfg’: 18, ‘is’: 19, ‘best’: 15}
方法 #2:使用字典理解 + sum()
这是可以执行此任务的另一种方式。这与上面的方法类似,只是一个简写版本。
# Python3 code to demonstrate working of
# Key Values Summations
# Using dictionary comprehension + sum()
# initializing dictionary
test_dict = {'gfg' : [4, 6, 8], 'is' : [9, 8, 2], 'best' : [10, 3, 2]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Key Values Summations
# Using dictionary comprehension + sum()
res = {key : sum(val) for key, val in test_dict.items()}
# printing result
print("The summation keys are : " + str(res))
输出 :
The original dictionary is : {‘gfg’: [4, 6, 8], ‘is’: [9, 8, 2], ‘best’: [10, 3, 2]}
The summation keys are : {‘gfg’: 18, ‘is’: 19, ‘best’: 15}