How can i replace a certain element in a list with an element from another list according to a condition

Adel Moustafa :

I am new to python and I want to build a function that updates part of a list according to a condition.

here is an example of what I want:

List1=[1,2,3,4,10,5,9,3,4]
List2=[2,4,6,8]

I want to update List1 to be [2,4,6,8,10,5,9,6,8], and here is my code to do that:

x = [1, 2, 3, 4, 10, 5, 9, 3, 4]
y = [2, 4, 6, 8]


def update_signal(gain):
    for i in range(0, len(y)):
        for j in range(0, len(x)):
            if x[j] == y[i] / gain:
                x[j] = y[i]
            elif x[j - 1] == y[i] / gain:
                break


update_signal(2)  # for this example only gain =2
print("x=", x)
print("y=", y)

the expected output is:

x=[2,4,6,8,10,5,9,6,8] 
y=[2,4,6,8]

what it actually prints is:

x= [8, 8, 6, 8, 10, 5, 9, 6, 8]
y= [2, 4, 6, 8]

so, what am I doing wrong to make this function behave like this?

Alexander Lekontsev :

Maybe something like this?

def update_signal(gain):
    return [item * gain if item * gain in y else item for item in x]

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=293708&siteId=1