[英]Applying a function to every possible combination of 2 keys in a dictionary
I have a very big dictionary that has a word as a key and a vector as value, something like this我有一个很大的字典,它有一个词作为键,一个向量作为值,像这样
groceries = {'apples': array([1,2,1],dtype=float32),
'bananas': array([1,3,4],dtype=float32),
'potatoes': array([1,4,4],dtype=float32)}
Each vector is a representation of score for the grocery shop manager.每个向量代表杂货店经理的分数。 I would like to find score for each possible combination of 2 keys.
我想为每个可能的 2 个键组合找到分数。 In this case a score for 'apples+bananas', score for 'bananas+potatoes', and score for 'apples+potatoes'.
在这种情况下,“apples+bananas”的分数、“bananas+potatoes”的分数和“apples+potatoes”的分数。
So, I need to calculate all the possible sums of every key value with every other key value.因此,我需要计算每个键值与每个其他键值的所有可能总和。 I have a function that takes 2 variables:
我有一个需要 2 个变量的函数:
def summing(u, v):
return u+v
This function takes variables and sums their values, so the sum for 'apples+bananas' should be [2,5,5]这个函数接受变量并对它们的值求和,所以“apples+bananas”的总和应该是 [2,5,5]
What would be a scaleable way to do it?什么是可扩展的方式来做到这一点? I am trying to work with itertools, but I haven't used it before and it became very messy.
我正在尝试使用 itertools,但我之前没有使用过它,它变得非常混乱。
You can do:你可以做:
sums = {key_combo: sum(groceries[k] for k in key_combo) for key_combo in itertools.combinations(groceries, 2)}
Explanation: itertools.combinations
creates all combinations.说明:
itertools.combinations
创建所有组合。 The dictionary comprehension sums the values for each combination and assigns the results to a dictionary keyed with the combinations.字典理解对每个组合的值求和,并将结果分配给以组合为键的字典。 Result is:
结果是:
sums
{('apples', 'bananas'): array([2., 5., 5.], dtype=float32),
('apples', 'potatoes'): array([2., 6., 5.], dtype=float32),
('bananas', 'potatoes'): array([2., 7., 8.], dtype=float32)}
The function summing
is not really necessary, as the numpy arrays know very well how to sum themselves.函数
summing
并不是真正必要的,因为 numpy 数组非常了解如何对自己求和。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.