📜  Python – 字典值均值

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

Python – 字典值均值

给定一个字典,找出所有存在值的平均值。

方法 #1:使用循环 + len()

这是可以执行此任务的粗暴方式。在此,我们遍历每个值并执行求和,然后将结果除以使用 len() 提取的总键。

Python3
# Python3 code to demonstrate working of 
# Dictionary Values Mean
# Using loop + len()
  
# initializing dictionary
test_dict = {"Gfg" : 4, "is" : 7, "Best" : 8, "for" : 6, "Geeks" : 10}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# loop to sum all values 
res = 0
for val in test_dict.values():
    res += val
  
# using len() to get total keys for mean computation
res = res / len(test_dict)
  
# printing result 
print("The computed mean : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Dictionary Values Mean
# Using sum() + len() + values()
  
# initializing dictionary
test_dict = {"Gfg" : 4, "is" : 7, "Best" : 8, "for" : 6, "Geeks" : 10}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# values extracted using values()
# one-liner solution to problem.
res = sum(test_dict.values()) / len(test_dict)
  
# printing result 
print("The computed mean : " + str(res))


输出
The original dictionary is : {'Gfg': 4, 'is': 7, 'Best': 8, 'for': 6, 'Geeks': 10}
The computed mean : 7.0

方法 #2:使用 sum() + len() + values()

上述功能的组合可以用来解决这个问题。在此,我们使用 sum() 和 size() 对使用 len() 计算的总键进行求和。

Python3

# Python3 code to demonstrate working of 
# Dictionary Values Mean
# Using sum() + len() + values()
  
# initializing dictionary
test_dict = {"Gfg" : 4, "is" : 7, "Best" : 8, "for" : 6, "Geeks" : 10}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# values extracted using values()
# one-liner solution to problem.
res = sum(test_dict.values()) / len(test_dict)
  
# printing result 
print("The computed mean : " + str(res)) 
输出
The original dictionary is : {'Gfg': 4, 'is': 7, 'Best': 8, 'for': 6, 'Geeks': 10}
The computed mean : 7.0