简体   繁体   English

两个向量之间的Python,DotProduct问题

[英]Python, DotProduct between two vectors issue

i'm trying to do a dot product between two vectors, but the problem is that they have to be simmetrical, now i explain what i mean. 我试图在两个向量之间做一个点积,但是问题是它们必须是对称的,现在我解释一下我的意思。

if i have two vectors like these: 如果我有两个这样的向量:

[('horse',2),('doll',34)]

[('horse',1),('monster',23),('salamander',12),('doll',17)]

in this case i will have two vectors of numerical values 在这种情况下,我将有两个数值向量

[2,34]
[1,23,12,17]

but to do a correct dot product i would like to have two vectors of the same lenght, and the values with the same word have to be in the same position, filling the not used positions with zeros. 但是要获得正确的点积,我希望有两个长度相同的向量,并且具有相同单词的值必须位于相同位置,并用零填充未使用的位置。

for example: 例如:

[2,0,0,34]
[1,23,12,17]

Any ideas how to transform the first vector in this way? 任何想法如何以这种方式转换第一个向量? I have to do it in python Thank you! 我必须在python中完成谢谢!

Using dict.get : 使用dict.get

>>> list1 = [('horse',2),('doll',34)]
>>> list2 = [('horse',1),('monster',23),('salamander',12),('doll',17)]

>>> d = dict(list1)  # => {'horse': 2, 'doll': 34}
>>> v2 = [value for name, value in list2]
>>> v1 = [d.get(name, 0) for name, value in list2]
>>> # d.get(name, 0) will return `0` for non-existing key (name).

>>> v1
[2, 0, 0, 34]
>>> v2
[1, 23, 12, 17]

>>> sum(x * y for x, y in zip(v1, v2))
580

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM