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

Merging two nested lists based on the index in Python

Hello my question has two parts.

First part : how to merge two nested lists based on the index , for example :

L1 = [[1,2],[4,5]]
L2 = [[11,22],[44,55]]

I want to merge the above nested lists based on their index so that i get an output like :

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

L3 = [ [[1,11],[2,22]] , [[4,44],[5,55]] ]

The second part of the problem is to add a constant value to all the nested lists so that the output is :

L3 = [ [[1,11,0],[2,22,0]] , [[4,44,0],[5,55,0]] ]

>Solution :

You can use a nested list comprehension with zip for both requirements:

>>> [[list(x) for x in zip(*t)] for t in zip(L1, L2)]
[[[1, 11], [2, 22]], [[4, 44], [5, 55]]]

and

>>> [[[a, b, 0] for a, b in zip(*t)] for t in zip(L1, L2)]
[[[1, 11, 0], [2, 22, 0]], [[4, 44, 0], [5, 55, 0]]]
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