3

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]

Andrea G
  • 63
  • 5
  • 2
    here's [an entry](https://stackoverflow.com/q/50554603/849891) asking for the exactly same thing, with answers in JS, Scala, and Scheme (and some pseudocode). – Will Ness Aug 16 '22 at 13:41

1 Answers1

4

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']]
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91