Skip to content Skip to sidebar Skip to footer

What Is The Pythonic Way To Calculate Dot Product?

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 defined as

Solution 1:

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)

Solution 2:

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))] )

Solution 3:

My favorite Pythonic dot product is:

sum([i*j for (i, j) in zip(list1, list2)])


So for your case we could do:

sum([i*j for (i, j) in zip([K[0] for K in A], B)])

Solution 4:

from operator import mul

sum(map(mul, A, B))

Solution 5:

Using the operator and the itertools modules:

from operator import mul
from itertools import imap

sum(imap(mul, A, B))

Post a Comment for "What Is The Pythonic Way To Calculate Dot Product?"