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 concatenate a list of sublists equally chunked

I have a list that contains sublists of two different types of items (for instance, cats and dogs). I also have a function chunk(list, n_sublists) that splits the list into n_sublists of equal size.

Then, i’d like to create a final list that merges the chunked lists from each type. An example:

cats_and_dogs = [ [dog1, dog2, dog3, dog4], [cat1, cat2] ]

splitted_chunks = [[[dog1, dog2], 
                    [dog3, dog4]],
                  [[cat1], 
                  [cat2]]] 

final_merged_sublists = [ [dog1, dog2, cat1], [dog3, dog4, cat2] ]

I hope the example makes it clear. However, i can provide more explanation if needed.

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

Thanks in advance.

>Solution :

You can do a loop on zip:

list(x+y for x,y in zip(chunk(dogs,2), chunk(cats,2))

Output:

[['dog1', 'dog2', 'cat1'], ['dog3', 'dog4', 'cat2']]

Update: in general, use reduce

from functools import reduce

splitted_chunks = map(lambda x: chunk(x,2), cats_and_dogs)
list(reduce(lambda x,y: x+y, z) for z in zip(*splitted_chunks) )
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