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.

Share:
58,586
hlin117
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, 2022

Comments

  • hlin117
    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's sum function.

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

  • wwii
    wwii almost 10 years
    option1 - sum(map(int, map(operator.itemgetter(1), table)))
  • hlin117
    hlin117 almost 10 years
    This answer works, but it creates a dictionary per row in the table. This isn't very memory efficient.
  • Peter Wood
    Peter Wood almost 10 years
    It 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
    Steven C. Howell about 3 years
    I expect this is using the reduce defined in functools. I just added that import.
  • rth
    rth about 3 years
    Thanks @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
    Luka Samkharadze over 2 years
    Please properly name your arguments, x and y 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.