Home > front end >  How to replace specific value in list of lists based on another list?
How to replace specific value in list of lists based on another list?

Time:03-25

It's possible to replace every specific value in a list of lists with the value from another list? Number of columns will be the same.

For this example, every single '1' will be replaced.

List1 = [[1,0,0,1,0] , [0,1,0,0,1]]

List2 = [4,6,8,17,19]

FinalList = [[4,0,0,17,0] , [0,6,0,0,19]

CodePudding user response:

You can convert List1 to a numpy array, multiply by List2, and then convert back to a list for a very fast (vectorized) and clean solution:

FinalList = (np.array(List1) * List2).tolist()

Output:

>>> FinalList
[[4, 0, 0, 17, 0], [0, 6, 0, 0, 19]]

CodePudding user response:

List1 = [[1,0,0,1,0] , [0,1,0,0,1]]

List2 = [4,6,8,17,19]

FinalList = List1.copy()

for l in range(len(List1)):
    for index, num in enumerate(List1[l]):
        if num == 1:
            FinalList[l][index] = List2[index]
            
print(FinalList)

Output: [[4, 0, 0, 17, 0], [0, 6, 0, 0, 19]]

It loops through every 1D list in List1, and loops through every number, if it is 1, it will replace it with the number at the corresponding index in List2.

Edit: If you are looking for a solution without numpy then this works, but in most practical cases, richardec's answer is much much better.

CodePudding user response:

You can try with panda

List = pd.DataFrame(List1).mul(List2).to_numpy().tolist()
Out[65]: [[4, 0, 0, 17, 0], [0, 6, 0, 0, 19]]
  • Related