Duplicating and pasting into a Python nested list
I currently have a nested list:
A = [[a1, a2, a3], c1, [a4, a5, a6], c2]
I also have another list:
B = [b1, b2]
I want to duplicate A by the number of elements in B and then insert the list B like this:
AB = [[a1, a2, a3], b1, c1, [a4, a5, a6], b1, c2, [a1, a2, a3], b2, c1, [a4, a5, a6], b2, c2]
The duplication I was able to find easily:
AB = A * len(B)
However, inserting a list into a nested list has me completely stumped.
I am currently using Python 3.6.1 and the size of list A and B can vary, but is always in the format:
A template = [[x1, x2, x3], z1 ...]
B template = [y1, ...]
Any help would be greatly appreciated.
+3
source to share
1 answer
You can do it in a simple way.
A = [['a1', 'a2', 'a3'], 'c1', ['a4', 'a5', 'a6'], 'c2']
AB=[]
B = ['b1', 'b2']
for i in B:
for j in A:
if isinstance(j,list):
AB.append(j)
else:
AB.append(i)
AB.append(j)
print AB
Output: [['a1', 'a2', 'a3'], 'b1', 'c1', ['a4', 'a5', 'a6'], 'b1', 'c2', ['a1', 'a2', 'a3'], 'b2', 'c1', ['a4', 'a5', 'a6'], 'b2', 'c2']
+2
source to share