How can I insert in the middle of a multilayered nested list?

Viewed 38

I am trying to create a program that inserts a list in the middle of another nested list. Like a sandwich sandwiching another sandwich and so on. I am trying to approach this recursively but I have no idea how.

for example

layer1 = [1,2,3,4]
layer2 = [1,2,3,4,5,6]
layer3 = [1,2,3]

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

Here's my code for context

def lasagna(N,i):
  mainLayers = formLayer(i)
  midpoint = len(mainLayers) // 2
  if i == N:
    return mainLayers
  elif i < N:
    mainLayers = mainLayers.insert(midpoint, formLayer(i))
  return lasagna(N,i+1)
2 Answers

You can use *args that accepts any number of arguments and then write a recursive function like so.

layer1 = [1,2,3,4]
layer2 = [1,2,3,4,5,6]
layer3 = [1,2,3]
layer4 = [1,2,3,4,5,6,7,8]
layer5 = [1,2,3,4]


def sandwhich(*seq):
    res = []
    if len(seq) == 1:
        return seq[0]
    res.extend(seq[0])
    res.insert(len(res) // 2, sandwhich(*seq[1:]))

    return res


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

print(sandwhich(layer1, layer2, layer3))
print(sandwhich(layer1, layer2, layer3, layer4, layer5))

Output

[1, 2, [1, 2, 3, [1, 2, 3], 4, 5, 6], 3, 4]
[1, 2, [1, 2, 3, [1, [1, 2, 3, 4, [1, 2, 3, 4], 5, 6, 7, 8], 2, 3], 4, 5, 6], 3, 4]

Slightly shorter recursive solution:

layer1 = [1,2,3,4]
layer2 = [1,2,3,4,5,6]
layer3 = [1,2,3]
def nest(vals):
  a, *b = vals
  return a[:len(a)//2]+([] if not b else [nest(b)]) + a[len(a)//2:]

print(nest([layer1, layer2, layer3]))

Output:

[1, 2, [1, 2, 3, [1, 2, 3], 4, 5, 6], 3, 4]
Related