📜  Python - 字典键的累积平均值

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

Python - 字典键的累积平均值

给定字典列表,我们的任务是编写一个Python程序来提取所有键的平均值。

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

在这种情况下,为了提取每个列表循环被使用,并且所有的值都使用字典相加和记忆。稍后通过除以每个键的出现来提取均值。



Python3
# Python3 code to demonstrate working of
# Cumulative Keys Mean in Dictionary List
# Using loop + mean()
from statistics import mean
  
# initializing list
test_list = [{'gfg' : 34, 'is' : 8, 'best' : 10},
             {'gfg' : 1, 'for' : 10, 'geeks' : 9, 'and' : 5, 'best' : 12},
             {'geeks' : 8, 'find' : 3, 'gfg' : 3, 'best' : 8}]
               
# printing original list
print("The original list is : " + str(test_list))
  
res = dict()
for sub in test_list:
    for key, val in sub.items():
        if key in res:
              
            # combining each key to all values in
            # all dictionaries
            res[key].append(val)
        else:
            res[key] = [val]
  
for key, num_l in res.items():
    res[key] = mean(num_l)
  
# printing result
print("The Extracted average : " + str(res))


Python3
# Python3 code to demonstrate working of
# Cumulative Keys Mean in Dictionary List
# Using defaultdict() + mean()
from statistics import mean
from collections import defaultdict
  
# initializing list
test_list = [{'gfg' : 34, 'is' : 8, 'best' : 10},
             {'gfg' : 1, 'for' : 10, 'geeks' : 9, 'and' : 5, 'best' : 12},
             {'geeks' : 8, 'find' : 3, 'gfg' : 3, 'best' : 8}]
               
# printing original list
print("The original list is : " + str(test_list))
  
# defaultdict reduces step to memoize.
res = defaultdict(list)
for sub in test_list:
    for key, val in sub.items():
        res[key].append(val)
          
res = dict(res)
for key, num_l in res.items():
      
    # computing mean
    res[key] = mean(num_l)
  
# printing result
print("The Extracted average : " + str(res))


输出:

方法 #2:使用defaultdict() + mean()

在这种情况下,记忆的任务是使用 defaultdict() 完成的。这减少了一次条件检查并使代码更加简洁。

蟒蛇3

# Python3 code to demonstrate working of
# Cumulative Keys Mean in Dictionary List
# Using defaultdict() + mean()
from statistics import mean
from collections import defaultdict
  
# initializing list
test_list = [{'gfg' : 34, 'is' : 8, 'best' : 10},
             {'gfg' : 1, 'for' : 10, 'geeks' : 9, 'and' : 5, 'best' : 12},
             {'geeks' : 8, 'find' : 3, 'gfg' : 3, 'best' : 8}]
               
# printing original list
print("The original list is : " + str(test_list))
  
# defaultdict reduces step to memoize.
res = defaultdict(list)
for sub in test_list:
    for key, val in sub.items():
        res[key].append(val)
          
res = dict(res)
for key, num_l in res.items():
      
    # computing mean
    res[key] = mean(num_l)
  
# printing result
print("The Extracted average : " + str(res))

输出: