How to compress multiple lists into one list and keeping the same size list?

Question:

I am trying to merge multiple lists that outputs 1 list of all the values and keep the zeros.
The indices and values need to be kept in the same index location.

Input:

list1 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 11, 0]
list2 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12]
list3 = [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
list4 = [0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0]
list5 = [0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0]
list6 = [0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0]
list7 = [0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0]
list8 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
list9 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
list10 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
list11 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
list12 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

This is what I want the output to be..

Output:

results = [1,0,0,4,5,6,7,0,0,0,11,12]
Asked By: jennytrinh96

||

Answers:

Loop over all the lists in parallel and sum the corresponding elements.

results = list(map(sum, zip(list1, list2, list3, list4, list5, list6, list7, list8, list9, list10, list11, list12)))
Answered By: Barmar
list_of_lists = [list1, list2, ...]

[sum(lst) for lst in zip(*list_of_lists)]

edit same as @Barmar’s answer, fundamentally — I didn’t see his answer at posting

Answered By: Kache

If you want to go with list comprehension and all lists have the same lengths..

results = []
for i in range(len(list1)):
    results.append(list1[i]+list2[i]+list3[i]+list4[i]+list5[i]+list6[i]+list7[i]+list8[i]+list9[i]+list10[i]+list11[i]+list12[i])

This would get the job done even though it’s ugly.

Answered By: Jack Arkmount
# coding=utf-8
import pandas as pd

data = [list1, list2, list3, list4, list5, list6, 
        list7, list8, list9, list10,list11, list12]

sum_l = pd.DataFrame(data).sum().tolist()

# [1, 0, 0, 4, 5, 6, 7, 0, 0, 0, 11, 12]
Answered By: Laurent B.
result = [*map(sum, zip(*[(eval(f'list{i}')) for i in range(1, 13)]))]
Answered By: ziying35
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.