What is the pythonic way to calculate dot product?

纵饮孤独 提交于 2019-11-28 04:57:24
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))] )
Henri Andre

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)

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

Using the operator and the itertools modules:

from operator import mul
from itertools import imap

sum(imap(mul, A, B))

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

>>> 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.

Aziz Alto

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 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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!