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
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
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.
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.
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])