1

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)
micgeronimo
  • 1,899
  • 5
  • 20
  • 40

4 Answers4

5

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
Moses Koledoye
  • 74,909
  • 8
  • 119
  • 129
3

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])
Ohumeronen
  • 1,517
  • 2
  • 11
  • 22
0

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
Rahul K P
  • 10,793
  • 3
  • 32
  • 47
0

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.

Community
  • 1
  • 1
Tonechas
  • 12,665
  • 15
  • 42
  • 74