简体   繁体   English

我如何在python中获得矢量的点积(列表形式)

[英]how can i get the dot product of vectors (list form) in python

we are given 2 sparse vectors v1 and v2 represented as Counters, we need to return their dot products. 我们给了2个稀疏向量v1和v2,表示为Counters,我们需要返回它们的点积。 what i have so far code wise: 到目前为止我有什么明智的代码:

import collections 

v1 = collections.Counter('aaabbbcccd')

v2 = collections.Counter('bcdd')

l1=list(v1.items())

l2=list(v2.items())

im not sure how to proceed from here because l1 and l2 contains: 我不确定如何从这里继续,因为l1和l2包含:

[('b', 3), ('c', 3), ('d', 1), ('a', 3)] [('b',3),('c',3),('d',1),('a',3)]

[('b', 1), ('c', 1), ('d', 2)] [('b',1),('c',1),('d',2)]

and i have no idea how to calculate the dot product from a list of this form. 而且我不知道如何从此表格的列表中计算点积。 (in this case would be 3*1 + 3*1 + 1*2 + 3*0 = 8) (在这种情况下为3 * 1 + 3 * 1 + 1 * 2 + 3 * 0 = 8)

also this code is suppose to work for vectors of arbitrary length, not just 4 该代码也适用于任意长度的向量,而不仅仅是4

any ideas would be appreciated. 任何想法,将不胜感激。

Just iterate over all the keys of either dict and sum the products (returning 0 for values which aren't present): 只需遍历任一dict的所有键并对乘积求和(对于不存在的值返回0):

sum(v1.get(k, 0) * v2.get(k, 0) for k in v1)

I didn't use the lists because it seems to me like it would complicate the problem unnecessarily... 我没有使用列表,因为在我看来,这似乎会使问题不必要地复杂化...


Also note that the answer I've provide works for any python dict. 还要注意,我提供的答案适用于任何 python dict。 For Counter instances, the second step gets even a bit simpler/cleaner: 对于Counter实例,第二步变得更加简单/简洁:

sum(v1[k] * v2[k] for k in v1)

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

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