0

I am trying to append elements from a multi-dimensional list into a 2nd multi-dimensional list. Here is the code I wrote -

my_list = [
    [["b", ["a"], "c"], ["d", ["a", "b"], "e"]],
    [["j", ["a", "f"]], ["q"]]
]

ref_list = [[["q", "w", "t"], ["y", "u"]], [["s"], ["p", "k", "l"]]]


for a, b in zip(my_list, ref_list):
    for i, subl in enumerate(a):
        for ii, v in enumerate(subl):
            if isinstance(v, list):
                subl[ii] = b[i] + subl[ii]
                break        
print(my_list)

The output I am getting is -

[
    [["b", ["q", "w", "t", "a"], "c"], ["d", ["y", "u", "a", "b"], "e"]],
    [["j", ["s", "a", "f"]], ["p", "k", "l", "q"]]
]

It adds elements of 2nd list to the beginneing of 1st list. The output I am trying to get is of sort -

[
    [["b", ["q", "a", "w", "a", "t", "a"], "c"], ["d", ["y", "a", "b", "u", "a", "b"], "e"]],
    [["j", ["s", "a", "f"]], ["p", "q", "k", "q", "l", "q"]]
]

I want to add inner_most element of my_list after each element of ref_list instead of just adding it once in the end.

2 Answers 2

1

Slight change to your code:

for a, b in zip(my_list, ref_list):
    for i, subl in enumerate(a):
        for ii, v in enumerate(subl):
            if isinstance(v, list):
                result = list()
                for element in b[i]:
                    result += [element]+subl[ii]
                subl[ii] = result
                break
        else:
            result = list()
            for element in b[i]:
                result += [element]+a[i]
            a[i] = result

>>> my_list
[[['b', ['q', 'a', 'w', 'a', 't', 'a'], 'c'],
  ['d', ['y', 'a', 'b', 'u', 'a', 'b'], 'e']],
 [['j', ['s', 'a', 'f']], ['p', 'q', 'k', 'q', 'l', 'q']]]
Sign up to request clarification or add additional context in comments.

Comments

1
my_list = [
    [["b", ["a"], "c"], ["d", ["a", "b"], "e"]],
    [["j", ["a", "f"]], ["q"]]
]

ref_list = [[["q", "w", "t"], ["y", "u"]], [["s"], ["p", "k", "l"]]]


for a, b in zip(my_list, ref_list):
    for i, subl in enumerate(a):
        for ii, v in enumerate(subl):
            if isinstance(v, list):
                new_subl=subl[ii]
                subl[ii]=[]
                for j in b[i]:
                    subl[ii] +=[j] + new_subl
                break

3 Comments

This doesn't give the output OP needs. You're missing an else block. mylist[-1] is [['j', ['s', 'a', 'f']], ['q']] instead of [['j', ['s', 'a', 'f']], ['p', 'q', 'k', 'q', 'l', 'q']]
but he wants to add to the inner_most element. to the 3rd element
See the expected output. Your answer does not give that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.