2

Is there any way to plus the first element of a list easily Wat I need to do is something like this:

Lista1 = [[5,7,6,4,3], [8,7,6,14,5],[5,7,8,6,9]]

Result

18  21  20  24  17
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
El arquitecto
  • 513
  • 2
  • 5
  • 16

3 Answers3

12

Of course there is a way:

map(sum, zip(*Lista1))

Here, zip(*Lista1) transposes Lista1, map(sum, ...) applies the sum function to each list of the transposed list.

ForceBru
  • 43,482
  • 10
  • 63
  • 98
3

One liner using list comprehension :

>>> [ sum(row[i] for row in l) for i in range(len(l[0])) ]

#driver values :

IN : l = [[5,7,6,4,3], [8,7,6,14,5],[5,7,8,6,9]]
OUT : [18, 21, 20, 24, 17]

NOTE : I would suggest going with the answers done using zip. More pythonic and better run time.

Kaushik NP
  • 6,733
  • 9
  • 31
  • 60
3

NumPy is a good method for achieving this. You can use np.sum and specify which axis you want to sum over. For example:

import numpy as np
a = np.array([[5,7,6,4,3],[8,7,6,14,5],[5,7,8,6,9]], dtype=int)
np.sum(a, axis=0)
array([18, 21, 20, 24, 17])
pacificgilly1992
  • 384
  • 3
  • 11
  • 3
    This is definitely overkill. I think you could do the same with a neural network with TensorFlow. – ForceBru Nov 04 '17 at 19:35
  • Yes, perhaps, but for large multidimensional arrays using the numpy method, this will provide a much-needed speed improvement due to the element-wise operations that numpy provides. – pacificgilly1992 Nov 04 '17 at 19:39