📜  Python程序在字典中查找key代表频率的值的总和

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

Python程序在字典中查找key代表频率的值的总和

给定一个带有值列表的字典,其中键代表频率,计算值列表中每个值的总出现次数。

方法:reduce() + Counter() + lambda + __add__

这是可以执行此任务的方式。其中,Counter() 用于计算每个值的频率,使用 __add__ 完成与键的求和,使用 reduce() 将每个键的所有值相加。 map() 用于将 Counter 的逻辑扩展到值列表中的每个值。

Python3
# Python3 code to demonstrate working of 
# Frequency Key Values Summation
# Using reduce() + Counter() + lambda + __add__
from functools import reduce
from collections import Counter
  
# initializing dictionary
test_dict = {70 : [7, 4, 6], 
             100 : [8, 9, 5], 
             200 : [2, 5, 3, 7], 
             50 : [6, 8, 5, 2]}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# Counter() used to get values mapped with keys 
# __add__ used to add key with values.
res = reduce(Counter.__add__, map(lambda sub: Counter({ele : sub[0] for ele in sub[1]}), 
                    test_dict.items()) )
# printing result 
print("Extracted Summation dictionary : " + str(dict(res)))


输出: