I got a problem where I cant exchange values in an array. I've got 2 arrays, one filled with zeros and ones, for example: disp = [[0.], [0.], [0.], [1.], [1.], [1.], [1.], [0.], [0.], [0.]]
and the other one filled with values I would like to implement at the place where the ones are in disp, for example: to_replace_at_1 = [[17.17], [0.], [-7.0] , [7.0]]
.
The result should look like this: disp = [[0.], [0.], [0.], [17.17], [0.], [-7.0], [7.0], [0.], [0.], [0.]]
.
I tried this:
for i in range(len(disp)):
vector = disp[i]
for value in vector:
if value == 1.0:
for e in to_replace_at_1:
disp[i] = to_replace_at_1[e]
But it ends up crashing. What should I try? How do I solve this?
CodePudding user response:
One way to do it:
iterator = iter(to_replace_at_1)
[x if x[0] != 1 else next(iterator) for x in disp]
CodePudding user response:
In your case it was crashing at disp[i] = to_replace_at_1[e]
since e
is a list in your case. Your logic implementation is good tho.
Not the best way I suppose but I can give you a working solution following code.
j = 0
for i in range(len(disp)):
vector = disp[i]
for value in vector:
if value == 1.0:
disp[i] = to_replace_at_1[j]
j = 1
CodePudding user response:
This will do :
disp = [[0.], [0.], [0.], [1.], [1.], [1.], [1.], [0.], [0.], [0.]]
to_replace_at_1 = [[17.17], [0.], [-7.0] , [7.0]]
idx = 0
for i, val in enumerate(disp):
if val[0] == 1.0:
disp[i] = to_replace_at_1[idx]
idx = 1
print(disp)
>>> [[0.0], [0.0], [0.0], [17.17], [0.0], [-7.0], [7.0], [0.0], [0.0], [0.0]]