How to replace ones with the values present in x?

Question:

In place of 1 , x values should be filled according to the index.

My code is :

x = [0.5697071 0.47144773 0.45310486]
z_prime= [[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1]]

flatten_matrix = [val for val in z_prime ]
for val in flatten_matrix:
for j in val:
if(j!=0):
z= x
else:
z = 0
print(z)

This gives the output as:

0

0

0

0

0

[0.5697071 0.47144773 0.45310486]

0

[0.5697071 0.47144773 0.45310486]

0

0

[0.5697071 0.47144773 0.45310486]

[0.5697071 0.47144773 0.45310486]

Expected Output:
[ [0, 0, 0], [0, 0, 0.45310486 ], [0, 0.47144773 , 0], [0, 0.47144773, 0.45310486],

Asked By: Reks

||

Answers:

Try this:

flatten_matrix = [[x[idx] if elm[idx] == 1 else 0 for idx in range(len(elm))] for elm in z_prime]

As a sidenote: I’d recommend breaking this up into a standalone function, because if you ever come back to this list comprehension it’ll be incomprehensible.
Consider something like this (which may be sligthly less performant, but much more readable)

def flatten_matrix(x, z_prime):
    if len(x) != len(z_prime[0]):
        raise ValueError("x and z_prime must have the same number of columns")
    #Maybe even add a check here that all the elements of z_prime are 0 or 1
    #Or add a check that all elements in z_prime have the same length?
    output = [[0] * len(x) for i in range(len(z_prime))] #Creates the output list with correct format
    for row_idx, elm in enumerate(z_prime): #Iterates through the rows of z_prime
        for col_idx, num in enumerate(elm): #Iterates through the columns of z_prime
            if num == 1:
                output[row_idx][col_idx] = x[col_idx]
            else:
                output[row_idx][col_idx] = 0
    return output
Answered By: Oren
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.