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.
Advertisement
Answer
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']]]