Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Working with nested lists in Python

list_ = [(1, 2), (3, 4)]

What is the Pythonic way of taking sum of ordered pairs from inner tuples and multiplying the sums? For the above example:

(1 + 3) * (2 + 4) = 24
like image 521
blackened Avatar asked Mar 13 '23 17:03

blackened


1 Answers

For example:

import operator as op
import functools
functools.reduce(op.mul, (sum(x) for x in zip(*list_)))

works for any length of the initial array as well as of the inner tuples.

Another solution using numpy:

import numpy as np
np.array(list_).sum(0).prod()
like image 51
eumiro Avatar answered Mar 23 '23 15:03

eumiro