I've got a problem where I want to place values in an array at certain matching values.
I've got displacement_gsj_values
filled with values I want to transplant, displacement_gsj_match
filled with the corresponding value match (in order) and displacement_all
a bigger array filled with corresponding matches of displacement_gsj.
Example:
displacement_gsj_values = [[-3.4],[0],[3.874],[7.4],[0.55],[-0.98],[0],[9.99],[-0.35]]
displacement_gsj_match = [[3],[4],[5],[9],[10],[11],[15],[16],[17]]
displacement_all = [[0],[0],[0],[3],[4],[5],[0],[0],[0],[9],[10],[11],[0],[0],[0],[9],[15],[11],[16],[4],[5],[9],[17],[11]]
I thought about a loop that should do this:
for i in displacement_all:
if i != 0:
if i in displacement_all[i] == displacement_gsj_match["any value of displacement_gsj_match with the same value of i"]:
displacement_all[i] = displacement_gsj_values["the index of the above matched value"]
else:
pass
It should place the values of displacement_gsj_values
with the corresponding index out of displacement_gsj_match
(both in order) into displacement_all at the matching value.
The result should look like this:
displacement_all = [[0],[0],[0],[-3.4],[0],[3.874],[0],[0],[0],[7.4],[0.55],[-0.98],[0],[0],[0],[7.4],[0],[-0.98],[9.99],[0],[3.874],[7.4],[-0.35],[-0.98]]
Had to post it again because someone just answered and then deleted his answer.
CodePudding user response:
I would first of all create a dictionary that maps values to their replacement:
# Flatten the list of lists
displacement_gsj_match = sum(displacement_gsj_match, [])
displacement_gsj_values = sum(displacement_gsj_values, [])
# Create dictionary with match as key and replacement as value
replacements = dict(zip(displacement_gsj_match, displacement_gsj_values))
Looks like this and makes substitution easier:
{3: -3.4,
4: 0,
5: 3.874,
9: 7.4,
10: 0.55,
11: -0.98,
15: 0,
16: 9.99,
17: -0.35}
Then you go over your list and check if the value can be replaced or stays the same. I used the get()
function, where the second argument is the default value. This means if the value is in the dictionary you replace it otherwise default to the existing value:
new_displacement = [[replacements.get(x[0], x[0])] for x in displacement_all]
Output:
[[0],
[0],
[0],
[-3.4],
[0],
[3.874],
[0],
[0],
[0],
[7.4],
[0.55],
[-0.98],
[0],
[0],
[0],
[7.4],
[0],
[-0.98],
[9.99],
[0],
[3.874],
[7.4],
[-0.35],
[-0.98]]
P.S.: This could be done in many ways, but I find this one pretty good to understand.
CodePudding user response:
The Pythonic way would be to directly use a comprehension:
[lst if lst[0] == 0
else displacement_gsj_values[displacement_gsj_match.index(lst)]
for lst in displacement_all]
which gives as expected:
[[0], [0], [0], [-3.4], [0], [3.874], [0], [0], [0], [7.4], [0.55], [-0.98], [0],
[0], [0], [7.4], [0], [-0.98], [9.99], [0], [3.874], [7.4], [-0.35], [-0.98]]