1

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]

3 Answers 3

2

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]]
Sign up to request clarification or add additional context in comments.

Comments

0
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.

Comments

0

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]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.