Duster
Duster

Reputation: 47

Appending elements from 1 list to nested elements of another list in one to one way in python

I have two lists and Id like to create new list with elements from list 1 appended to the elements in list 2 in almost a one-to-one way.

My lists are as fallows,

list1=[[m, g],[n, b]]
list2=[[[['a'], ['b']],[['c'], ['d']]], [[['a'], ['f']],[['g'],['d']]]]

Id like the first element in list1 to be appended with the elements inside the first nested list in list2, and similarly the second element in list1 to be appended to each elements in the second element in list2.

The outcome would look something like this,

newlist=[[[[['a'], ['b']], [m, g]], [[['c'], ['d']], [m, g]]],
 [[[['a'], ['f']], [n, b]], [[['g'], ['d']], [n, b]]]]

Ive tried doing this,

newlist=[]
for i in range(len(list2)):
    f=map(list, zip(list2[i], list1))
    newlist.append(f)

newlist=[[[[['a'], ['b']], [m, g]], [[['c'], ['d']], [n, b]]],
 [[[['a'], ['f']], [m, g]], [[['g'], ['d']], [n, b]]]]

but the outcome is not exactly what I need. Any help on how to fix this would help.

Upvotes: 0

Views: 56

Answers (1)

IoaTzimas
IoaTzimas

Reputation: 10624

Here is my suggestion:

result=[]
for i,k in zip(list2, list1):
    result.append([[x,k] for x in i])

print(result)

Output:

[[[[['a'], ['b']], ['m', 'g']], [[['c'], ['d']], ['m', 'g']]], [[[['a'], ['f']], ['n', 'b']], [[['g'], ['d']], ['n', 'b']]]]

Upvotes: 2

Related Questions