Reputation: 160
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?
Upvotes: 4
Views: 159
Reputation: 11
x=[1,2,3,4,10,5,9,3,4]
y=[2,4,6,8]
def update_signal(gain):
for i in range(len(x)):
for j in range(len(y)):
if y[j]//x[i]==gain:
x[i]=y[j]
break
Upvotes: 1
Reputation: 21
Please try the code below:
x = [1, 2, 3, 4, 10, 5, 9, 3, 4]
x_copy = x[:]
y = [2, 4, 6, 8]
def update_signal(gain):
for i in range(0, len(y)):
cond = y[i] / gain
for j in range(0, len(x)):
if x[j] == cond:
x_copy[j] = y[i]
elif x[j - 1] == cond:
continue
update_signal(2) # for this example only gain =2
print("x=", x_copy)
print("y=", y)
Upvotes: 1
Reputation: 2596
I assume that your algorithm means:
i
is x
's arbitrary element.j
is y
's arbitrary element.i
is same with j / gain
, replace i
to j
(If I am wrong, point it please. Then I'll fix for it.)
x = [1, 2, 3, 4, 10, 5, 9, 3, 4]
y = [2, 4, 6, 8]
def update_signal(gain):
convert_table = {i / gain: i for i in y}
x[:] = [convert_table.get(i, i) for i in x]
update_signal(2) # for this example only gain =2
print('x = ', x)
print('y = ', y)
output:
x = [2, 4, 6, 8, 10, 5, 9, 6, 8]
y = [2, 4, 6, 8]
Upvotes: 1
Reputation: 1012
Maybe something like this?
def update_signal(gain):
return [item * gain if item * gain in y else item for item in x]
Upvotes: 1