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

Unpack a single element from a list of lists python

I have zipped some data into as following:

list1 = [1,33,3]
list2 = [2,44,23]
list3 = [[3,4,5,6],[3,4,5,3],[4,5,3,1]]
list4 = [4,34,4]

data = [list(x) for x in zip(list1, list2, list3, list4)]

However, list3 is a list of lists. So the output ended up being

[[1,2,[3,4,5,6],4],
 [33,44,[3,4,5,3],34], 
 [3,23,[4,5,3,1],4]]

I would like to unpack the list inside the lists like the following:

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

[[1,2,3,4,5,6,4],
 [33,44,3,4,5,3,34], 
 [3,23,4,5,3,1,4]]

What is the best way to do that in python?

Cheers

>Solution :

You could use iteration_utilities.deepflatten in a list comprehension:

>>> from iteration_utilities import deepflatten
>>> xs1 = [1, 33, 3]
>>> xs2 = [2, 44, 23]
>>> xs3 = [[3, 4, 5, 6], [3, 4, 5, 3], [4, 5, 3, 1]]
>>> xs4 = [4, 34, 4]
>>> data = [list(xs) for xs in zip(xs1, xs2, xs3, xs4)]
>>> data
[[1, 2, [3, 4, 5, 6], 4], [33, 44, [3, 4, 5, 3], 34], [3, 23, [4, 5, 3, 1], 4]]
>>> new_data = [list(deepflatten(xs)) for xs in data]
>>> new_data
[[1, 2, 3, 4, 5, 6, 4], [33, 44, 3, 4, 5, 3, 34], [3, 23, 4, 5, 3, 1, 4]]
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