How to sum columns of an array in Python

How do I add all column values ​​in a python array? Ideally, I want to do this without importing any additional libraries.

input_val = [[1, 2, 3, 4, 5],
             [1, 2, 3, 4, 5],
             [1, 2, 3, 4, 5]]

output_val = [3, 6, 9, 12, 15]

I know this can be done in a nested loop, wondering if there was a better way (e.g. list comprehension)?

+6
source share
10 answers

zipand sumcan be performed:

Code:

[sum(x) for x in zip(*input_val)]

ziptakes the contents of the input list and transfers it so that each element of the contained lists is created at the same time. This allows sumyou to see the first elements of each contained list, then the next iteration will receive the second element of each list, etc.

Test code:

input_val = [[1, 2, 3, 4, 5],
             [1, 2, 3, 4, 5],
             [1, 2, 3, 4, 5]]

print([sum(x) for x in zip(*input_val)])

:

[3, 6, 9, 12, 15]
+12

sum zip map:

# In Python 3.x 
>>> list(map(sum, zip(*input_val)))
[3, 6, 9, 12, 15]
# explicitly type-cast it to list as map returns generator expression

# In Python 2.x, explicit type-casting to list is not needed as `map` returns list
>>> map(sum, zip(*input_val))
[3, 6, 9, 12, 15]
+3

:

[sum(i) for i in zip(*input_val)]
+2

:

input_val = [[1, 2, 3, 4, 5],
         [1, 2, 3, 4, 5],
         [1, 2, 3, 4, 5]]

output_val = [sum([i[b] for i in input_val]) for b in range(len(input_val[0]))]

print output_val
+2

,

map(sum, [x for x in zip(*input_val)])
+2

, numpy :

np.sum(input_val, = 0)

+1

: ( ), .

output_val = [sum([input_val[i][j] for i in range(len(input_val))]) \
                 for j in range(len(input_val[0]))]
+1

, :

import numpy as np
new_list = sum(map(np.array, input_val))
+1

. output_val [3, 6, 9, 12, 15] input_val:

input_val = [[1, 2, 3, 4, 5],
             [1, 2, 3, 4, 5],
             [1, 2, 3, 4, 5]]

vals_length = len(input_val[0])
output_val = [0] * vals_length # init empty output array with 0's
for i in range(vals_length): # iterate for each index in the inputs
    for vals in input_val:
        output_val[i] += vals[i] # add to the same index

print(output_val) # [3, 6, 9, 12, 15]
0
output_val=input_val.sum(axis=0)

. ,

0
source

Source: https://habr.com/ru/post/1016592/


All Articles