点积与字典 [英] Dot product with dictionaries
本文介绍了点积与字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将两个字典的值做点积.例如:
I am trying to do a dot product of the values of two dictionaries. For example:
dict_1={'a':2, 'b':3, 'c':5, 'd':2}
dict_2={'a':2, 'b':2, 'd':3, 'e':5 }
以列表形式,上面看起来像这样:
In list form, the above looks like this:
dict_1=[2,3,5,2,0]
dict_2=[2,2,0,3,5]
具有相同键的字典的点积将导致:
The dot product of the dictionary with the same key would result in:
Ans= 16 [2*2 + 3*2 + 5*0 + 2*3 + 0*5]
如何用字典来做到这一点?使用该列表,我可以调用np.dot
函数或编写一个小循环.
How can I achieve this with the dictionary? With the list, I can just invoke the np.dot
function or write a small loop.
推荐答案
在通过对dict_2进行迭代的dict_1键与get()函数结合使用的列表中使用sum函数:
Use sum function on list produced through iterate dict_1 keys in couple with get() function against dict_2:
dot_product = sum(dict_1[key]*dict_2.get(key, 0) for key in dict_1)
这篇关于点积与字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文