问题
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:
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))] )
回答2:
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)
回答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)])
回答4:
from operator import mul
sum(map(mul, A, B))
回答5:
Using the operator and the itertools modules:
from operator import mul
from itertools import imap
sum(imap(mul, A, B))
回答6:
Probably the most Pythonic way for this kind of thing is to use numpy. ;-)
回答7:
>>> 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.
回答8:
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
回答9:
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
回答10:
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
来源:https://stackoverflow.com/questions/5919530/what-is-the-pythonic-way-to-calculate-dot-product