📜  Python - 字典列表所有值求和

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

Python - 字典列表所有值求和

给定一个字典列表,提取所有值的总和。

方法#1:使用循环

这是可以执行此任务的粗暴方式。在此,我们迭代列表中的所有字典,然后对每个字典的所有键进行求和。

Python3
# Python3 code to demonstrate working of 
# List of dictionaries all values Summation
# Using loop
  
# initializing lists
test_list = [{"Gfg" : 6, "is" : 9, "best" : 10}, 
             {"Gfg" : 8, "is" : 11, "best" : 19},
             {"Gfg" : 2, "is" : 16, "best" : 10},
             {"Gfg" : 12, "is" : 1, "best" : 8},
             {"Gfg" : 22, "is" : 6, "best" : 8}]
  
# printing original list
print("The original list : " + str(test_list))
  
res = 0
# loop for dictionaries
for sub in test_list:
    for key in sub:
          
        # summation of each key 
        res += sub[key]
      
# printing result 
print("The computed sum : " + str(res))


Python3
# Python3 code to demonstrate working of 
# List of dictionaries all values Summation
# Using sum() + values() + list comprehension
  
# initializing lists
test_list = [{"Gfg" : 6, "is" : 9, "best" : 10}, 
             {"Gfg" : 8, "is" : 11, "best" : 19},
             {"Gfg" : 2, "is" : 16, "best" : 10},
             {"Gfg" : 12, "is" : 1, "best" : 8},
             {"Gfg" : 22, "is" : 6, "best" : 8}]
  
# printing original list
print("The original list : " + str(test_list))
  
res = sum([sum(list(sub.values())) for sub in test_list])
      
# printing result 
print("The computed sum : " + str(res))


输出
The original list : [{'Gfg': 6, 'is': 9, 'best': 10}, {'Gfg': 8, 'is': 11, 'best': 19}, {'Gfg': 2, 'is': 16, 'best': 10}, {'Gfg': 12, 'is': 1, 'best': 8}, {'Gfg': 22, 'is': 6, 'best': 8}]
The computed sum : 148

方法 #2:使用 sum() + values() + 列表理解

上述功能的组合可以作为一种替代方案来解决这个问题。在此,使用 sum() 执行求和,使用 values() 提取列表中所有字典的值。

Python3

# Python3 code to demonstrate working of 
# List of dictionaries all values Summation
# Using sum() + values() + list comprehension
  
# initializing lists
test_list = [{"Gfg" : 6, "is" : 9, "best" : 10}, 
             {"Gfg" : 8, "is" : 11, "best" : 19},
             {"Gfg" : 2, "is" : 16, "best" : 10},
             {"Gfg" : 12, "is" : 1, "best" : 8},
             {"Gfg" : 22, "is" : 6, "best" : 8}]
  
# printing original list
print("The original list : " + str(test_list))
  
res = sum([sum(list(sub.values())) for sub in test_list])
      
# printing result 
print("The computed sum : " + str(res))
输出
The original list : [{'Gfg': 6, 'is': 9, 'best': 10}, {'Gfg': 8, 'is': 11, 'best': 19}, {'Gfg': 2, 'is': 16, 'best': 10}, {'Gfg': 12, 'is': 1, 'best': 8}, {'Gfg': 22, 'is': 6, 'best': 8}]
The computed sum : 148