Working with nested lists in Python

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

What is the Python way to take the sum of ordered pairs from inner tuples and multiply the sums? For the above example:

(1 + 3) * (2 + 4) = 24
+4
source share
2 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 for internal tuples.

Another solution using numpy :

import numpy as np
np.array(list_).sum(0).prod()
+7
source

If the lists are small, as implied, I believe that using operatorand itertoolsfor something like this applies a sledgehammer to the nut. Similarly numpy. What is wrong with pure Python?

result = 1
for s in [ sum(x) for x in zip( *list_) ]: 
  result *= s

( , Python product, sum). , 2- , - .

result = (list_[0][0]+list_[1][0] )*( list_[0][1]+list_[1][1])
0

Source: https://habr.com/ru/post/1622750/


All Articles