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 :
result = A[0][0] * B[0] + A[1][开发者_Go百科0] * B[1] + ... + A[n-1][0] * B[n-1]
I know the logic is easy but how to write in pythonic way?
Thanks!
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))] )
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)])
from operator import mul
sum(map(mul, A, B))
Using the operator and the itertools modules:
from operator import mul
from itertools import imap
sum(imap(mul, A, B))
Using more_itertools
, a third-party library that implements the dotproduct
itertools recipe:
import more_itertools as mit
a = [1, 2, 3]
b = [7, 8, 9]
mit.dotproduct(a, b)
# 50
>>> X = [2,3,5,7,11]
>>> Y = [13,17,19,23,29]
>>> dot = lambda X, Y: sum(map(lambda x, y: x * y, X, Y))
>>> dot(X, Y)
652
And that's it.
People are re-assigning the @ operator as the dot product operator. Here's my code using vanilla python's zip which returns a tuple. Then uses list comprehension instead of map.
def dot_product(a_vector,b_vector):
#a1 x b1 + a2 * b2..an*bn return scalar
return sum([an*bn for an,bn in zip(a_vector,b_vector)])
X = [2,3,5,7,11]
Y = [13,17,19,23,29]
print(dot_product(X,Y)) #652
a=[1,2,3]
b=[4,5,6]
print(dot_product(a,b)) #prints 32= 1*4 + 2*5 + 3*6 =
a = [1, 2, 3]
b = [7, 8, 9]
print(dot_product(a,b)) #prints 50
Probably the most Pythonic way for this kind of thing is to use numpy. ;-)
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
精彩评论