Reputation: 33
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!
Upvotes: 0
Views: 229
Reputation: 369244
Using 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
Upvotes: 2