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:
JavaScript
x
9
1
cats_and_dogs = [ [dog1, dog2, dog3, dog4], [cat1, cat2] ]
2
3
splitted_chunks = [[[dog1, dog2],
4
[dog3, dog4]],
5
[[cat1],
6
[cat2]]]
7
8
final_merged_sublists = [ [dog1, dog2, cat1], [dog3, dog4, cat2] ]
9
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:
JavaScript
1
2
1
list(x+y for x,y in zip(chunk(dogs,2), chunk(cats,2))
2
Output:
JavaScript
1
2
1
[['dog1', 'dog2', 'cat1'], ['dog3', 'dog4', 'cat2']]
2
Update: in general, use reduce
JavaScript
1
5
1
from functools import reduce
2
3
splitted_chunks = map(lambda x: chunk(x,2), cats_and_dogs)
4
list(reduce(lambda x,y: x+y, z) for z in zip(*splitted_chunks) )
5