34

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?

hlin117
  • 20,764
  • 31
  • 72
  • 93

6 Answers6

60

One approach is to use a generator expression:

total = sum(int(v) for name,v in table)
Peter de Rivaz
  • 33,126
  • 4
  • 46
  • 75
13

reduce can help

from functools import reduce

total = reduce(lambda accumulator,element:accumulator+int(element[1]), table,0)
rth
  • 2,946
  • 1
  • 22
  • 27
  • 1
    I expect this is using the `reduce` defined in `functools`. I just added that import. – Steven C. Howell Apr 27 '21 at 14:06
  • 1
    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 – rth Apr 28 '21 at 15:43
  • 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. – Luka Samkharadze Jan 11 '22 at 23:09
11

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

total = sum(map(lambda x: int(x[1]), table))
FredrikHedman
  • 1,223
  • 7
  • 14
3
sum(map(int,zip(*table)[-1]))

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

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
2

You can also get at the values in a dictionary:

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

This may be a little obscure.

Peter Wood
  • 23,859
  • 5
  • 60
  • 99
  • 2
    This answer works, but it creates a dictionary per row in the table. This isn't very memory efficient. – hlin117 Jul 30 '14 at 22:15
  • 1
    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. – Peter Wood Jul 31 '14 at 09:42
0

One way is using indexing.

total=sum(items[1] for items in table)
4b0
  • 21,981
  • 30
  • 95
  • 142
SRG
  • 345
  • 1
  • 9