Search code examples
pythoncomputationdot-productmathematical-expressions

Python dot-multiply lists on list of lists, without using numpy


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.


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