blackened
blackened

Reputation: 903

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

Upvotes: 4

Views: 223

Answers (2)

nigel222
nigel222

Reputation: 8192

If the lists are small as is implied, I feel that using operator and itertools for something like this is applying a sledgehammer to a nut. Likewise numpy. What is wrong with pure Python?

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

(although it would be a lot nicer if pure Python had a product built-in as well as sum ). Also if you are specifically dealing only with pairs of 2-tuples then any form of iteration is a sledgehammer. Just code

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

Upvotes: 0

eumiro
eumiro

Reputation: 212825

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()

Upvotes: 7

Related Questions