micgeronimo
micgeronimo

Reputation: 2149

Python sum and then multiply values of several lists

Is there way to write following code in one line?

my_list = [[1, 1, 1], [1, 2], [1, 3]]
result = 1
for l in list:
    result = result * sum(l)

Upvotes: 1

Views: 1047

Answers (4)

Tonechas
Tonechas

Reputation: 13723

Maybe there are some people out there who think that a one-liner which requires an import statement is not a true one-liner. Just for fun, those who think so might prefer this admittedly obfuscated solution to the approaches suggested so far:

In [389]: (lambda f: lambda n: f(f, n))(lambda rec, x: 1 if not x else x[0]*rec(rec, x[1:]))(map(sum, my_list))
Out[389]: 36

The code above relies on the built-in functions map() and sum() to compute the sums of the sublists, and on recursive calls to a lambda function to compute the product of the sums.

Upvotes: 0

Moses Koledoye
Moses Koledoye

Reputation: 78556

Use reduce on the summed sublists gotten from map.

This does it:

>>> from functools import reduce
>>> reduce(lambda x,y: x*y, map(sum, my_list))
36

In python 2.x, the import will not be needed as reduce is a builtin:

>>> reduce(lambda x,y: x*y, map(sum, my_list))
36

Upvotes: 5

Rahul K P
Rahul K P

Reputation: 16081

with numpy

In [1]: from numpy import prod
In [2]: prod([sum(i) for i in my_list])
Out[2]: 36

Another method.

In [1]: eval('*'.join(str(item) for item in [sum(i) for i in my_list]))
Out[1]: 36

Upvotes: 0

Ohumeronen
Ohumeronen

Reputation: 2086

Here you go:

import operator
my_list = [[1, 1, 1], [1, 2], [1, 3]]
print reduce(operator.mul, [sum(l) for l in my_list])

Upvotes: 3

Related Questions