-2

Hi I have an array that I want to sum the elements vertically. Just wonder are there any functions can do this easily ?

a = [[ 1,  2,  3,  4,  5],
         [ 6,  7,  8,  9, 10],
         [11, 12, 13, 14, 15],
         [16, 17, 18, 19, 20],
         [21, 22, 23, 24, 25]]

I want to print the answers of 1+6+11+16+21 , 2+7+12+17, 3+8+13, 4+9, 5 As you can see, in each iteration, there is one element less.

Osca
  • 1,588
  • 2
  • 20
  • 41
  • Have a look here: https://stackoverflow.com/questions/30062429/python-how-to-get-every-first-element-in-2-dimensional-list – Jeppe Jan 23 '19 at 08:43
  • 3
    You may not really find a pre-built function that does a sum this way because it is fairly "specific" to this problem and not always useful in general. Try *attempting a solution first* and see what you come up with. If you get stuck while attempting a solution, then we can try to help. Show us a *good faith effort* – Paritosh Singh Jan 23 '19 at 08:44
  • There is no specific function for this but you can use `sum(list_comprehension)` for this. – Arpit Svt Jan 23 '19 at 08:45
  • What have you tried so far? – Cleared Jan 23 '19 at 08:50

2 Answers2

4

This is one approach using zip and a simple iteration.

Ex:

a = [[ 1,  2,  3,  4,  5],
         [ 6,  7,  8,  9, 10],
         [11, 12, 13, 14, 15],
         [16, 17, 18, 19, 20],
         [21, 22, 23, 24, 25]]

print([sum(v[:-i]) if i else sum(v) for i, v in enumerate(zip(*a))])

Output:

[55, 38, 24, 13, 5]
Rakesh
  • 81,458
  • 17
  • 76
  • 113
0

Converting to a numpy array, and then using the following list comprehension

a = np.array(a)
[a[:5-i,i].sum() for i in range(5)]

yields the following:

[55, 38, 24, 13, 5]
Joe Patten
  • 1,664
  • 1
  • 9
  • 15