Home > Software design >  How to concatenate a list of sublists equally chunked
How to concatenate a list of sublists equally chunked

Time:12-10

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.

CodePudding user response:

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) )

CodePudding user response:

You can use zip and itertools.chain:

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

from itertools import chain
final_merged_sublists = [list(chain.from_iterable(x)) for x in zip(*splitted_chunks)]

Output:

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

NB. To apply chunk on all sublists of the original list of arbitrary size, use map

CodePudding user response:

Just for fun, you can zip the lists and flatten each sublist of subsublists:

def flatten_list(list1):
    out = []
    inside = list1
    while inside:
        x = inside.pop(0)
        if isinstance(x, list):
            inside[0:0] = x
        else:
            out.append(x)
    return out

out = [flatten_list(list(x)) for x in zip(*splitted_chunks)]

Output:

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