Finding a sum in nested list using a lambda function
58,586
Solution 1
One approach is to use a generator expression:
total = sum(int(v) for name,v in table)
Solution 2
reduce can help
from functools import reduce
total = reduce(lambda accumulator,element:accumulator+int(element[1]), table,0)
Solution 3
If you want to use lambda the following should solve it:
total = sum(map(lambda x: int(x[1]), table))
Solution 4
sum(map(int,zip(*table)[-1]))
is one way to do it ... there are many options however
Solution 5
You can also get at the values in a dictionary:
total = sum(map(int, dict(table).values())
This may be a little obscure.
Author by
hlin117
Software Engineer at Uber Technologies. Previously student at the University of Illinois at Urbana-Champaign. Interests include Machine Learning Bioinformatics Mathematics
Updated on January 13, 2022Comments
-
hlin117 over 2 years
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'ssum
function.What's the pythonic/functional way to sum up the second column?
-
wwii almost 10 yearsoption1 -
sum(map(int, map(operator.itemgetter(1), table)))
-
hlin117 almost 10 yearsThis answer works, but it creates a dictionary per row in the table. This isn't very memory efficient.
-
Peter Wood almost 10 yearsIt creates just one dictionary using the table, and iterates over the values converting each one to an integer, and then sums them. For a big table it could be prohibitive. @PeterdeRivaz's answer using a generator is the most Pythonic.
-
Steven C. Howell about 3 yearsI expect this is using the
reduce
defined infunctools
. I just added that import. -
rth about 3 yearsThanks @StevenC.Howell for clarification! In 2014, the answer was in Python2 where reduce is the basic functions. Yes for Python3
reduce
must be imported -
Luka Samkharadze over 2 yearsPlease properly name your arguments,
x
andy
are not any helpful. I quickly wanted to know which one is sum and which one is current. Your "answer" isn't any helpful on that.