-1

I am getting an output from an SQL query in the form of an array of tuples. The array looks like this-

(1, 100)
(2, 150)
(3, 200)

I want to find the sum of the columns seperately. Thus, I want to get the value 1+2+3= 6 for column 1, and also get the value 100+150+200= 450 for column 2.

When I use the built-in var1=sum(arr[0]), I get 101, which is the sum of the first row instead of column.

How do I add up the first column in the easiest manner?

sbhatla
  • 1,040
  • 2
  • 22
  • 34

1 Answers1

1

You can use zip and a list comprehension:

>>> lst = [
...     (1, 100),
...     (2, 150),
...     (3, 200)
... ]
>>> list(zip(*lst))  # zip(*lst) groups the items that you want to sum
[(1, 2, 3), (100, 150, 200)]
>>>
>>> [sum(x) for x in zip(*lst)]
[6, 450]
>>>
  • Could you explain the `*` usage? – sbhatla Jul 02 '14 at 18:39
  • It unpacks the items in `lst` as arguments to `zip`. In this case, doing `zip(*lst)` is short for `zip((1, 100), (2, 150), (3, 200))` –  Jul 02 '14 at 18:42