sharathchandramandadi
sharathchandramandadi

Reputation: 540

Replace multiple items in a list of list from another list of list of indices and values

I have a list1 below:

   list1 = [[(0, 8), (2, 9), (3, 9)],
 [(0, 10), (2, 9), (3, 9)],
 [(0, 11), (2, 12), (3, 12)]]

This list of lists contains tuples with index as first item and value as second item. I need to replace the values at particular index in the list2 below with the values from list1 above. Both list1 and list2 will be of same length and indices in the list of lists will be with in the range:

list2 = [[[], [], [], [], [], [], []],
 [[], [], [], [], [], [], []],
 [[], [], [], [], [], [], []]]

The expected output is :

output = [[8, [], 9, 9, [], [], []],
 [10, [], 9, 9, [], [], []],
 [11, [], 12, 12, [], [], []]]

I tried the following code:

def replist(x,y):
    for i in x:
        for m,n in i:
            y[m]=n
            
output = [replist(list1, i) for i in list2]

output = [[11, [], 12, 12, [], [], []],
 [11, [], 12, 12, [], [], []],
 [11, [], 12, 12, [], [], []]]

I know the issue with my code and also its not a correct way of replacing items in list in this fashion, but wanted to know if there is a way to do the replacement.

I checked many stackoverflow links with some similar questions, but they involved replacing a single list.

Upvotes: 0

Views: 655

Answers (1)

Dschoni
Dschoni

Reputation: 3862

You could change the function itself to work directly on the list:

list1 = [[(0, 8), (2, 9), (3, 9)],
         [(0, 10), (2, 9), (3, 9)],
         [(0, 11), (2, 12), (3, 12)]]

list2 = [[[], [], [], [], [], [], []],
         [[], [], [], [], [], [], []],
         [[], [], [], [], [], [], []]]

def replist(input_list,output_list):
    for list_index, entry in enumerate(input_list):
        for sub_index, value in entry:
            output_list[list_index][sub_index]=value
    return output_list
            

output = replist(list1, list2)

Upvotes: 1

Related Questions