0

the question is pretty clear but an example:

a = [[1,2],[3,4],[5,6],[7,8]]

then the list I want to make is:

a_new = [ 1+3+5+7 , 2+4+6+8]

The lists within the list are always of the same length and of course I want to not only do this for two dimensions but for big numbers n as well.

So far I've tried using double for loops but I utterly failed so help would be much appreciated.

Kees Til
  • 171
  • 1
  • 17
  • Debugging and implementation questions are off topic on Programmers.SE and best asked on StackOverflow (as described in the [help/on-topic]). –  Sep 23 '14 at 22:05

3 Answers3

6

Use the zip() function to transpose your input lists from rows to columns, then sum() those columns:

[sum(col) for col in zip(*a)]

Demo:

>>> a = [[1,2],[3,4],[5,6],[7,8]]
>>> zip(*a)
[(1, 3, 5, 7), (2, 4, 6, 8)]
>>> [sum(col) for col in zip(*a)]
[16, 20]
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
0

Using map:

>>> a = [[1,2],[3,4],[5,6],[7,8]]
>>> map(sum, zip(*a))
[16, 20]
>>>
James Sapam
  • 16,036
  • 12
  • 50
  • 73
0

Instead of using map(), zip(), or reduce(), here is a pure list comprehension method using list concatenation:

[sum([x for x, y in a])]+[sum([y for x, y in a])]

>>> a = [[1,2],[3,4],[5,6],[7,8]]
>>> a_new = [sum([x for x, y in a])]+[sum([y for x, y in a])]
>>> a_new
[16, 20]
>>> 
A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76