Python Forum

Full Version: Changing elements of a list to match another list
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am trying to iterate through a list of list and increase the first element in each sublist until it matches an integer on another list...

list1=[[2,13,22,40],[8,13,22,40],[24,13,22,40]]
reference_list=[5, 10, 30]
for i in list1: 
    while i[0]!=i in reference_list:        
        i[0]=i[0]+1
print(list1)
Right now my output is:

[[2, 13, 22, 40], [8, 13, 22, 40], [24, 13, 22, 40]]
(Nothing is getting modified) My desired output is:

[[5, 13, 22, 40], [10, 13, 22, 40], [30, 13, 22, 40]]
(so that the first integer is increased until it matches an integer on the reference_list)

I have dabbled using the set function but I can't seem to get that to work.

Any ideas are appreciated!
If I correctly understand the objective then no iteration is needed.

You just want to replace first element in every row in matrix with value which in reference list. As indexes of rows in matrixes and elements in reference list are the same one can just:

>>> lst = [[2,13,22,40],[8,13,22,40],[24,13,22,40]]                  
>>> reference = [5, 10, 30]                                          
>>> for i, v in enumerate(reference): 
...     lst[i][0] = v 
...
>>> lst                                                              
[[5, 13, 22, 40], [10, 13, 22, 40], [30, 13, 22, 40]]
My understanding was he wanted the first value in the sublist to be the lowest value in reference_list that is greater than or equal to the original value. So his while condition should be while i[0] not in reference_list:.

But I agree the problem is not clearly defined.