I have two lists, one is named as A, another is named as B. Each element in A is a triple, and each element in B is just an number. I would like to calculate the result defi
Python 3.5 has an explicit operator @
for the dot product,
so you can write
a = A @ B
instead of
a = numpy.dot(A,B)
import numpy
result = numpy.dot( numpy.array(A)[:,0], B)
http://docs.scipy.org/doc/numpy/reference/
If you want to do it without numpy, try
sum( [a[i][0]*b[i] for i in range(len(b))] )
from operator import mul
sum(map(mul, A, B))
This might be repeated solution, however:
>>> u = [(1, 2, 3), (4, 5, 6)]
>>> v = [3, 7]
In plain Python
:
>>> sum([x*y for (x, *x2), y in zip(u,v)])
31
Or using numpy
(as described in user57368's answer) :
import numpy as np
>>> np.dot(np.array(u)[:,0], v)
31
All above answers are correct, but in my opinion the most pythonic way to calculate dot product is:
>>> a=[1,2,3]
>>> b=[4,5,6]
>>> sum(map(lambda pair:pair[0]*pair[1],zip(a,b)))
32
Using the operator and the itertools modules:
from operator import mul
from itertools import imap
sum(imap(mul, A, B))