Reputation: 11
I would like to ask whether it is possible to create a dot product within this nested list a = [[1,2,3],[2,4,2],[1,2,3], [5,6,7]] in Python without using numpy
I tried:
a = [[1,2,3],[2,4,2],[1,2,3], [5,6,7]]
for x, y in zip(a):
temp = []
for m, n in zip(x):
temp.append(m * n)
c.append([sum(temp)])
print(c)
However I got an error message:
not enough values to unpack (expected 2, got 1)
Upvotes: 0
Views: 338
Reputation: 40908
You can unpack and zip a
, then use operator
and reduce
(built-in in Python 2.x):
>>> from functools import reduce
>>> from operator import mul
>>> sum(reduce(mul, i) for i in zip(*a))
232
In other words:
>>> i, j, k = zip(*a)
>>> i
(1, 2, 1, 5)
>>> j
(2, 4, 2, 6)
>>> k
(3, 2, 3, 7)
Then you take sum( (1*2*1*5, 2*4*2*6, 3*2*3*7) )
.
Upvotes: 1