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.
Thanks in advance.
Advertisement
Answer
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) )