Add integers of an array in python

2

This is a simple question but I have not found any post related to this topic.

matriz=[[1,2,3],[4,5,6][7,8,9]]

I would like to add all the grids of this matrix to each other (1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9) so that I returned 45 in a new variable. (Something with two for cycles, one inside another?)

Could this also be done?:

var_1=1
var_2=1+2
var_3=1+2+3
var_4=1+2+3+4
var_5=...

So on with all the grids of the matrix, a greeting, thank you.

    
asked by Nexobeta28 YT 23.05.2018 в 23:43
source

2 answers

3

You can use two for nested, the first iterates over the rows and the second over the elements of each row and use a variable to store the sum as you comment:

suma = 0
for fila in matriz:
    for n in fila:
        suma += n

However using the built-in sum is more efficient, in order to apply it one possibility is to flatten the list first and then apply sum . In addition to the forms that @Ale shows in its response we can use itertools.chain.from_iterable

>>> import itertools
>>> matriz = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> sum(itertools.chain.from_iterable(matriz))
45

The second thing that you propose is not more than an accumulated sum, for it itertools also has the solution, itertools.accumulate :

>>> cumsum = list(itertools.accumulate(itertools.chain.from_iterable(matriz)))
>>> cumsum
[1, 3, 6, 10, 15, 21, 28, 36, 45]

The normal thing is to use a list or other iterable one to store the accumulated sums, but if you want to use 9 variables simply unpack:

>>> cumsum = itertools.accumulate(itertools.chain.from_iterable(matriz))
>>> var_1, var_2, var_3, var_4, var_5, var_6, var_7, var_8, var_9 = cumsum
    
answered by 24.05.2018 / 10:26
source
2

You can use sum() with a generator expression here:

>>> matriz=[[1,2,3],[4,5,6],[7,8,9]]
>>> suma = sum(sum(x) for x in matriz)
>>> print(suma)
>>> 45

or also as follows

>>> matriz=[[1,2,3],[4,5,6],[7,8,9]]
>>> suma = sum(sum(matriz, []))
>>> print(suma)
>>> 45
    
answered by 24.05.2018 в 00:07