Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiply all lists in list of lists

Tags:

python

I have a list of masks and I want to obtain the resulting mask by multiplying all of them. My Donkey Kong approach is the following:

a = [[1, 1], [1, 0], [1, 0]]
b = a[0]
for i in range(1, len(a)):
    b = b * np.array(a[i])

which I think it works as returns [1,0] as value of b.

Is there a nicer way of doing this?


EDIT: I am looking for common ranges in the mask. To find all the non zero ranges I do the following: label = 0

for i in range(1, len(labels)):
   label = label + np.array(labels[i])
label = [1 if x > 0 else 0 for x in label]
like image 342
shamalaia Avatar asked Sep 30 '21 08:09

shamalaia


People also ask

How do you multiply all elements in a list by another list in Python?

The zip() function in python can combine the contents of 2 or more iterables. Zip Function returns a zipped output. We can then simply store the output in Result and Display it on the console. This is a very simple way to perform list multiplication in Python.

How do you multiply a nested list in Python?

We use the * operator to multiply the elements of the second list with respective elements of the nested list.

Can you multiply lists in Python?

Lists and strings have a lot in common. They are both sequences and, like pythons, they get longer as you feed them. Like a string, we can concatenate and multiply a Python list.

How do you multiply a range in Python?

Use a list comprehension to multiply each number in a range by specific number, e.g. result = [num * 2 for num in range(1, 6)] . The list comprehension iterates over the range and uses the multiplication * operator to multiply the current number by another number.


3 Answers

Take a look at np.prod, which returns the product of array elements over a given axis:

import numpy as np
a = [[1, 1], [1, 0], [1, 0]]
np.prod(a, axis=0)
like image 190
Seon Avatar answered Oct 20 '22 20:10

Seon


I see that you are already using numpy so it can be used like other answers suggested. But still, a nice built-in solution only using reduce can be:

from functools import reduce

a = [[1, 1], [1, 0], [1, 0]]

def element_wise_multiply(list1, list2):
    return [x*y for x,y in zip(list1, list2)]

b = reduce(element_wise_multiply, a)

# Or as a lambda:
b = reduce(lambda list1, list2: [x*y for x,y in zip(list1, list2)], a)

This takes every two sub-lists and reduces them to one by multiplying all index-matching elements by using zip. It also gives:

[1, 0]
like image 4
Tomerikoo Avatar answered Oct 20 '22 19:10

Tomerikoo


Use np.prod:

>>> np.prod(a, axis=0)
array([1, 0])
>>> 

Or you could use np.cumprod and get the last value:

>>> np.cumprod(a, axis=1)[-1]
array([1, 0], dtype=int32)
>>> 
like image 1
U12-Forward Avatar answered Oct 20 '22 21:10

U12-Forward