Python程序在字典中查找key代表频率的值的总和
给定一个带有值列表的字典,其中键代表频率,计算值列表中每个值的总出现次数。
Input : test_dict = {70 : [7, 4, 6], 50 : [6, 8, 5, 2]}
Output : {7: 70, 4: 70, 6: 120, 8: 50, 5: 50, 2: 50}
Explanation : 6 occurs in both keys, hence 70 + 50 = 120, assigned to 6.
Input : test_dict = {70 : [7, 4], 50 : [6, 8, 5, 2]}
Output : {7: 70, 4: 70, 6: 50, 8: 50, 5: 50, 2: 50}
Explanation : 6 now occurs in only 50 key, hence only 50 is assigned.
方法: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)))
输出:
The original dictionary is : {70: [7, 4, 6], 100: [8, 9, 5], 200: [2, 5, 3, 7], 50: [6, 8, 5, 2]}
Extracted Summation dictionary : {7: 270, 4: 70, 6: 120, 8: 150, 9: 100, 5: 350, 2: 250, 3: 200}