1

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.

smci
  • 32,567
  • 20
  • 113
  • 146
AJW
  • 5,569
  • 10
  • 44
  • 57

3 Answers3

6
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)]
Eric
  • 95,302
  • 53
  • 242
  • 374
  • Never heard of `operator` before. What does this `col, 1`do here? – AJW Mar 27 '14 at 13:03
  • Could use some explanation; `zip(*rows)` transposes the matrix, and what do they arguments to `reduce` do. – RemcoGerlich Mar 27 '14 at 13:03
  • `operator.mul` is just a shorthand for `lambda a, b: a * b`. Look at the documentation for reduce – Eric Mar 27 '14 at 13:04
  • thanks Eric - your solution is very elegant. Thank you for introducing me to `operator` and `reduce`. Accepted your answer. – AJW Mar 27 '14 at 13:06
  • @tobias_k: what is your answer the solution for? – AJW Mar 27 '14 at 13:16
  • @AJW Just another way to check whether all the numbers are one, which is equivalent to multiplying them, if they are all just zero or one. If they are not all zero/one, you might want to edit your question accordingly. – tobias_k Mar 27 '14 at 13:19
0

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.

user189
  • 604
  • 3
  • 11
0

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

Yuv
  • 202
  • 3
  • 12