# Help to get summation list of lists generated iteratively

2

I have developed a program with which I generate a list in each round of a total of 5 rounds. I add these lists to a list of lists called my_list_tot. The code is as follows:

``````import random

mi_lista_tot=[]

for round in range(5):
mi_lista=[]
mi_lista_tot.append(mi_lista)

a1=[random.randrange(2) for i in range(8)]
a2=[random.randrange(2) for i in range(8)]
a3=[random.randrange(2) for i in range(8)]

for n in range(len(a1)):
mi_lista.append(a1[n] + a2[n] + a3[n])

print mi_lista_tot
``````

In the current output, what I am generating is a list of lists of the following type:

``````[[2, 2, 1, 2, 2, 2, 2, 2], [2, 2, 1, 0, 1, 2, 0, 3], [2, 1, 2, 0, 1, 1, 3, 3], [2, 1, 2, 2, 1, 2, 2, 1], [1, 1, 2, 0, 0, 0, 0, 2]]
``````

However, I would like my_list_tot to generate a summation list of the values in each index. In this case:

``````[9, 7, 8, 6, 5, 7, 7, 11]
``````

It's what I can not do. I appreciate comments.

asked by pyring 02.10.2017 в 22:35
source

2

Without modifying your code too much you can use `zip` or `itertools.izip` (which uses an iterator similar to what `zip` does in Python 3, decreasing the use of memory) next to `sum` to add `a1` , `a2` and `a3` in each round and then add the rounds between themselves:

``````import itertools
import random

mi_lista_tot=[]

for round in range(5):
a1=[random.randrange(2) for i in range(8)]
a2=[random.randrange(2) for i in range(8)]
a3=[random.randrange(2) for i in range(8)]

mi_lista_tot.append([sum(x) for x in itertools.izip(a1,  a2, a3)])

mi_lista_tot = [sum(x) for x in itertools.izip(*mi_lista_tot)]
print mi_lista_tot
``````

If you did not use `a1` , `a2` and `a3` or the lists of each round for nothing else you could simply do:

``````import itertools
import random

mi_lista_tot = [sum(r) for r in itertools.izip(*[[random.randrange(2) for i in range(8)]
for _ in range (5*3)])]
print(mi_lista_tot)
``````