📜  Python|字典列表值的总和

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

Python|字典列表值的总和

有时,在使用Python字典时,我们可以将其值作为列表。在这种情况下,我们可能会遇到一个问题,即我们只需要将这些列表中的元素计数作为一个整体。这可能是数据科学中的一个问题,我们需要在观察中获取总记录。让我们讨论可以执行此任务的某些方式。

方法 #1:使用sum() + 列表推导
可以使用 sum函数执行此任务,该函数可用于获取总和,并且内部列表理解可以提供一种机制来将此逻辑迭代到字典的所有键。

# Python3 code to demonstrate working of
# Summation of dictionary list values
# using sum() + list comprehension
  
# initialize dictionary
test_dict = {'gfg' : [5, 6, 7], 'is' : [10, 11], 'best' : [19, 31, 22]}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# Summation of dictionary list values
# using sum() + list comprehension
res = sum(len(sub) for sub in test_dict.values())
  
# printing result
print("Summation of dictionary list values are : " + str(res))
输出 :
The original dictionary is : {'best': [19, 31, 22], 'is': [10, 11], 'gfg': [5, 6, 7]}
Summation of dictionary list values are : 8

方法#2:使用sum() + map()
也可以使用 map函数代替列表推导来执行此任务,以扩展查找长度的逻辑,其余所有功能与上述方法相同。

# Python3 code to demonstrate working of
# Summation of dictionary list values
# using sum() + map()
  
# initialize dictionary
test_dict = {'gfg' : [5, 6, 7], 'is' : [10, 11], 'best' : [19, 31, 22]}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# Summation of dictionary list values
# using sum() + map()
res = sum(map(len, test_dict.values()))
  
# printing result
print("Summation of dictionary list values are : " + str(res))
输出 :
The original dictionary is : {'best': [19, 31, 22], 'is': [10, 11], 'gfg': [5, 6, 7]}
Summation of dictionary list values are : 8