Bharat Bittu
Bharat Bittu

Reputation: 525

How to divide list of list in Python 3?

list1 = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0],
         [0, 500000.0, 500000.0, 500000.0], [0, 0, 1000000.0, 0],
         [0, 1000000.0, 500000.0, 2500000.0]]

list2 = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0],
         [0, 1, 1, 1], [0, 0, 2, 0], [0, 2, 1, 4]]

Can we divide each element from list1 and list2?

Output should again be in lists of list.

Upvotes: 2

Views: 273

Answers (3)

rafaelc
rafaelc

Reputation: 59274

IIUC

import numpy as np
>>> np.array(list1)/list2
array([[    nan,     nan,     nan,     nan],
       [    nan,     nan,     nan,     nan],
       [    nan,     nan,     nan,     nan],
       [    nan,     nan,     nan,     nan],
       [    nan, 500000., 500000., 500000.],
       [    nan,     nan, 500000.,     nan],
       [    nan, 500000., 500000., 625000.]])

Upvotes: 5

Adam Smith
Adam Smith

Reputation: 54213

This is commonly known as zipwith. Python doesn't have a builtin function to do this, but it's easy to build yourself with a list comprehension.

[f(a, b) for a, b in zip(list1, list2)]  # where f is the function to zip with!

This is actually a zipwith of zipwiths, though, so let's nest:

[[aa/bb for (aa, bb) in zip(a, b)] for (a, b) in zip(list1, list2)]

EDIT: as Aran-Fey points out, zipwith does exist as map in Python, which makes this:

import functools
import operator

zipwithdiv = functools.partial(map, functools.partial(map, operator.truediv))

zipwithdiv(list1, list2)  # magic!

which is, admittedly, uglier than sin. But it makes my little functional heart go a-pitter patter.

Upvotes: 5

Pierluigi
Pierluigi

Reputation: 1118

You can try the following using the built-in function zip:

result = []
for sub_list1, sub_list2 in zip(list1, list2):
    sub_list = []
    for a, b in zip(sub_list1, sub_list2):
        if b == 0:
            sub_list.append('DivisionByZero')
            continue
        sub_list.append(a / b)
    result.append(sub_list)

this will produce:

[['DivisionByZero', 'DivisionByZero', 'DivisionByZero', 'DivisionByZero'],
 ['DivisionByZero', 'DivisionByZero', 'DivisionByZero', 'DivisionByZero'],
 ['DivisionByZero', 'DivisionByZero', 'DivisionByZero', 'DivisionByZero'],
 ['DivisionByZero', 'DivisionByZero', 'DivisionByZero', 'DivisionByZero'],
 ['DivisionByZero', 500000.0, 500000.0, 500000.0],
 ['DivisionByZero', 'DivisionByZero', 500000.0, 'DivisionByZero'],
 ['DivisionByZero', 500000.0, 500000.0, 625000.0]]

Upvotes: 0

Related Questions