I am trying to append elements from a multi-dimensional list into a 2nd multi-dimensional list. Here is the code I wrote –
JavaScript
x
16
16
1
my_list = [
2
[["b", ["a"], "c"], ["d", ["a", "b"], "e"]],
3
[["j", ["a", "f"]], ["q"]]
4
]
5
6
ref_list = [[["q", "w", "t"], ["y", "u"]], [["s"], ["p", "k", "l"]]]
7
8
9
for a, b in zip(my_list, ref_list):
10
for i, subl in enumerate(a):
11
for ii, v in enumerate(subl):
12
if isinstance(v, list):
13
subl[ii] = b[i] + subl[ii]
14
break
15
print(my_list)
16
The output I am getting is –
JavaScript
1
5
1
[
2
[["b", ["q", "w", "t", "a"], "c"], ["d", ["y", "u", "a", "b"], "e"]],
3
[["j", ["s", "a", "f"]], ["p", "k", "l", "q"]]
4
]
5
It adds elements of 2nd list to the beginneing of 1st list. The output I am trying to get is of sort –
JavaScript
1
5
1
[
2
[["b", ["q", "a", "w", "a", "t", "a"], "c"], ["d", ["y", "a", "b", "u", "a", "b"], "e"]],
3
[["j", ["s", "a", "f"]], ["p", "q", "k", "q", "l", "q"]]
4
]
5
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:
JavaScript
1
20
20
1
for a, b in zip(my_list, ref_list):
2
for i, subl in enumerate(a):
3
for ii, v in enumerate(subl):
4
if isinstance(v, list):
5
result = list()
6
for element in b[i]:
7
result += [element]+subl[ii]
8
subl[ii] = result
9
break
10
else:
11
result = list()
12
for element in b[i]:
13
result += [element]+a[i]
14
a[i] = result
15
16
>>> my_list
17
[[['b', ['q', 'a', 'w', 'a', 't', 'a'], 'c'],
18
['d', ['y', 'a', 'b', 'u', 'a', 'b'], 'e']],
19
[['j', ['s', 'a', 'f']], ['p', 'q', 'k', 'q', 'l', 'q']]]
20