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?
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.
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.
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.
One approach is to use a generator expression:
total = sum(int(v) for name,v in table)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With