Reputation: 115
I have 2 lists, and for the A list, which is made up of sublists, I'd like to insert all the elements from a second list, B, into a speciifc index within the sublists.
The two lists are as fallows,
A=[[[a, b], [c, d], [g, h]]
[[e, f], [g, h], [t, f]]]
B=[[d, c], [e, j]]
The wanted out put would look like this, with each element from B added into the 2nd spot in A,
A=[[[a, b], [d, c], [c, d], [g, h]],
[[a, b], [e, j], [c, d], [g, h]],
[[e, f], [d, c], [g, h], [t, f]],
[[e, f], [e, j], [g, h], [t, f]]]
So for each sublist in A, the elements of B get added into the 2nd spot in A. Im sure there needs to a 'copy' elements, as each sublist in A needs to get copied to account for the 2 different elements in B, but Im not sure how to go about coding this. Any input is appreciated.
Upvotes: 1
Views: 279
Reputation: 36624
I hope you appreciate the half hour I put on this one-liner solution:
[*map(lambda a, b: (a[0], b, a[1:]), *([i for s in [*map(lambda x: (x, x), A)] for i in s], B*2))]
[(['a', 'b'], ['d', 'c'], [['c', 'd'], ['g', 'h']]),
(['a', 'b'], ['e', 'j'], [['c', 'd'], ['g', 'h']]),
(['e', 'f'], ['d', 'c'], [['g', 'h'], ['t', 'f']]),
(['e', 'f'], ['e', 'j'], [['g', 'h'], ['t', 'f']])]
Upvotes: 2
Reputation: 1952
This was a fun challenge! Good question.
def insertInto(A,B,i) -> list:
output_list = []
for a_list in A:
for b_list in B:
new_list = a_list[::]
new_list.insert(i-1,b_list)
output_list.append(new_list)
return output_list
A=[[["a", "b"], ["c", "d"], ["g", "h"]],
[["e", "f"], ["g", "h"], ["t", "f"]]]
B=[["d", "c"], ["e", "j"]]
C=[[["a", "b"], ["d", "c"], ["c", "d"], ["g", "h"]],
[["a", "b"], ["e", "j"], ["c", "d"], ["g", "h"]],
[["e", "f"], ["d", "c"], ["g", "h"], ["t", "f"]],
[["e", "f"], ["e", "j"], ["g", "h"], ["t", "f"]]]
assert insertInto(A,B,2) == C
Upvotes: 1