Reputation: 5873
I am quite new to python and getting my head around arrays as such, and I am struck on a rather simple problem. I have a list of list, like so:
a = [[1,0,1,0,1],[0,0,1,0,1],[0,0,1,0,1],[1,1,1,0,1],[1,0,0,0,0]]
and I would like to multiply elements of each list with each other. Something like:
a_dot = [1,0,1,0,1]*[0,0,1,0,1]*[0,0,1,0,1]*[1,1,1,0,1]*[1,0,1,0,0]
=[0,0,1,0,0]
Was wondering if I can do the above without using numpy/scipy.
Thanks.
Upvotes: 1
Views: 1043
Reputation: 202
You can solve by below code,
def multiply(list_a,list_b):
c = []
for x,y in zip(list_a,list_b):
c.append(x*y)
return c
reduce(lambda list_a,list_b: multiply(list_a,list_b), a)
Happy coding!!!!
Upvotes: 0
Reputation: 97631
import operator
a_dot = [reduce(operator.mul, col, 1) for col in zip(*a)]
But if all your data is 0s and 1s:
a_dot = [all(col) for col in zip(*a)]
Upvotes: 6
Reputation: 604
Did you try the reduce function? You call it with a function (see it as your operator) and a list and it applies it the way you described.
Upvotes: 0