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][0] * B[1] + ... + A[n-1][0] * B[n-1] 

I know the logic is easy but how to write in pythonic way?

Thanks!

1

11 Answers

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) 
5
import numpy result = numpy.dot( numpy.array(A)[:,0], B) 

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)]) 
1
from operator import mul sum(map(mul, A, B)) 
0

Using the operator and the itertools modules:

from operator import mul from itertools import imap sum(imap(mul, A, B)) 
1

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.

Probably the most Pythonic way for this kind of thing is to use numpy. ;-)

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 

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 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy