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

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:

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

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']]
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