Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Output:

results = [1,0,0,4,5,6,7,0,0,0,11,12]

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading