0

I have a list that looks like this and I would like to sum up the values at each position so as produce a list with only three values

print x
[[0, 0, -1], [0, 0, -1], [0, 0, 0], [1, 0, 0], [0, 0, 1]]

For example, x[0][1] should be summed with the value in x[1][1], x[2][1], x[3][1], x[4][1]. Likewise x[0][2] should be summed with x[1][2], x[2][2], etc.

the output should look like this

print output
[1, 0, -1]
user3067923
  • 437
  • 2
  • 14

3 Answers3

3

Using numpy:

np.sum(x, axis=0) 

Using native list:

[sum(y) for y in zip(*x)]
Julien
  • 13,986
  • 5
  • 29
  • 53
3

I would use Julien's answer as it is more readable but to give you an alternative, you can use map and zip functions.

list(map(sum, zip(*x)))
umutto
  • 7,460
  • 4
  • 43
  • 53
0

Just combine for loops:

outlist=[]
for i in range(len(L[0])):
    sum = 0
    for subL in L:
        sum += subL[i]
    outlist.append(sum)

print(outlist)

Output:

[1, 0, -1]
rnso
  • 23,686
  • 25
  • 112
  • 234