Search code examples
pythonlistreshapeshapesflatten

flatten an irregular list and reshape another same-lenght flat list reconstructuning the original element order


Take an irregularly shaped list such as:

L = [[[1,2,3],[4,5],6]

(by irregularly shaped I mean whatever irregular shape, not just the irregular one I used as example). Now make it flat as described here obtaining

L_flat = [1,2,3,4,5,6]

Take now a new list with the same shape of the flat one such as:

L_flat_new = [a,b,c,d,e,f]

how can I reconstruct this new list to have the same shape of the original one element-wise?

desired output: L_flat_new_reshaped = [[[a,b,c],[d,e],f]


Solution

  • Try recursion:

    L = [[[1, 2, 3], [4, 5], 6]]
    
    L_flat_new = ["a", "b", "c", "d", "e", "f"]
    
    
    def reshape(orig, i):
        if isinstance(orig, list):
            return [reshape(v, i) for v in orig]
        else:
            return next(i)
    
    
    print(reshape(L, iter(L_flat_new)))
    

    Prints:

    [[['a', 'b', 'c'], ['d', 'e'], 'f']]