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?
Answers:
One approach is to use a generator expression:
total = sum(int(v) for name,v in table)
sum(map(int,zip(*table)[-1]))
is one way to do it … there are many options however
reduce can help
from functools import reduce
total = reduce(lambda accumulator,element:accumulator+int(element[1]), table,0)
If you want to use lambda the following should solve it:
total = sum(map(lambda x: int(x[1]), table))
You can also get at the values in a dictionary:
total = sum(map(int, dict(table).values())
This may be a little obscure.
One way is using indexing.
total=sum(items[1] for items in table)
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?
One approach is to use a generator expression:
total = sum(int(v) for name,v in table)
sum(map(int,zip(*table)[-1]))
is one way to do it … there are many options however
reduce can help
from functools import reduce
total = reduce(lambda accumulator,element:accumulator+int(element[1]), table,0)
If you want to use lambda the following should solve it:
total = sum(map(lambda x: int(x[1]), table))
You can also get at the values in a dictionary:
total = sum(map(int, dict(table).values())
This may be a little obscure.
One way is using indexing.
total=sum(items[1] for items in table)