Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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.

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top