Finding a sum in nested list using a lambda function

Question:

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?

Asked By: hlin117

||

Answers:

One approach is to use a generator expression:

total = sum(int(v) for name,v in table)
Answered By: Peter de Rivaz
sum(map(int,zip(*table)[-1]))

is one way to do it … there are many options however

Answered By: Joran Beasley

reduce can help

from functools import reduce

total = reduce(lambda accumulator,element:accumulator+int(element[1]), table,0)
Answered By: rth

If you want to use lambda the following should solve it:

total = sum(map(lambda x: int(x[1]), table))
Answered By: FredrikHedman

You can also get at the values in a dictionary:

total = sum(map(int, dict(table).values())

This may be a little obscure.

Answered By: Peter Wood

One way is using indexing.

total=sum(items[1] for items in table)
Answered By: SRG