Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding a sum in nested list using a lambda function

I have a data structure similar to this

table = [     ("marley", "5"),     ("bob", "99"),     ("another name", "3") ] 

What I would like to do, to get the sum of the 2nd column (5 + 99 + 3) functionally like this:

total = sum(table, lambda tup : int(tup[1])) 

That would be similar syntax to the python function sorted, but that's not how you would use python's sum function.

What's the pythonic/functional way to sum up the second column?

like image 865
hlin117 Avatar asked Jul 30 '14 21:07

hlin117


People also ask

How do you get the sum of a nested list?

We can find sum of each column of the given nested list using zip function of python enclosing it within list comprehension. Another approach is to use map(). We apply the sum function to each element in a column and find sum of each column accordingly.

Can lambda functions be nested?

A lambda function inside a lambda function is called a nested lambda function. Python allows lambda nesting, i.e., you can create another lambda function inside a pre-existing lambda function. For nesting lambdas, you will need to define two lambda functions – an outer and an inner lambda function.

Can lambda functions be used to iterate through a list?

First off, the Lambda function itself cannot be used to iterate through a list. Lambda, by its very nature, is used to write simple functions without the use of defining them beforehand.


1 Answers

One approach is to use a generator expression:

total = sum(int(v) for name,v in table) 
like image 196
Peter de Rivaz Avatar answered Sep 20 '22 00:09

Peter de Rivaz