edesz
edesz

Reputation: 12406

Python replace list elements in 2 lists, at indexes of substrings in 3rd list

I have the following 3 Python lists:

cl_ambient = ['BRy', 'WilmB', 'Hgan', 'FoVx', 'Afree', 'FoVx_d', 'Afree_d']
temp_farh = ['grey', 'DarkOrange', 'r', 'black', 'black', 'black', 'black']
manual_calib = ['white', 'white', 'white', 'blue', 'yellow', 'green', 'darkgreen']

All 3 lists will always have the same length.

Start with the list cl_ambient:

I need to find the indexes of the elements in cl_ambient which is a substring of another element. In this case, the indexes of such elements are at indexes 3,5 (Fovx,Fovx_d) and 4,6 (Afree,Afree_d).

Now, once these indexes are found, I need to use these indexes to make replacement in both of the other 2 lists:

I need to replace the higher index element from the other 2 lists (temp_farh and manual_calib) with the lower index element from the manual_calib list. So, if we do this manually, the replacements should be:

temp_farh[5] = temp_farh[3]
temp_farh[6] = temp_farh[4]

manual_calib[5] = temp_farh[3]
manual_calib[6] = temp_farh[4]

I need to make these replacements programmatically. I cannot do this manually since the lists are likely to be quite long.

Required Output:

The output should be:

cl_ambient = ['BRy', 'WilmB', 'Hgan', 'FoVx', 'Afree', 'FoVx_d', 'Afree_d']
temp_farh = ['grey', 'DarkOrange', 'r', 'black', 'black', 'blue', 'yellow']
manual_calib = ['white', 'white', 'white', 'blue', 'yellow', 'blue', 'yellow']

Question:

Is there a way to extract these substring elements programmatically from these 3 lists?

Additional Information:

  1. As per the comment below, I will add this: there will not be a scenario where more than 2 substrings exists in the cl_ambient list. Example: FoVx, FoVx_d, FoVx_a will not exist. There will only be Fovx_d OR Fovx_a.
  2. The substring will always be before the longer element in the cl_ambient list.

Upvotes: 0

Views: 208

Answers (1)

ShmulikA
ShmulikA

Reputation: 3744

the answer is splitted into two parts, first find the desired indexes we want to replace and then make the replace

the code:

cl_ambient = ['BRy', 'WilmB', 'Hgan', 'FoVx', 'Afree', 'FoVx_d', 'Afree_d']
temp_farh = ['grey', 'DarkOrange', 'r', 'black', 'black', 'black', 'black']
manual_calib = ['white', 'white', 'white', 'blue', 'yellow', 'green', 'darkgreen']


# for each index search match on the higher indexes, 
# if found save it on the changes list as (high, low) tuple
changes = [(i+1+j, i) for i, s1 in enumerate(cl_ambient)
           for j, s2 in enumerate(cl_ambient[i+1:]) 
           if (s1 in s2 or s2 in s1)]
print(changes)

# do the change on both lists
for i, j in changes:
    temp_farh[i] = manual_calib[j]
    manual_calib[i] = manual_calib[j]

print(temp_farh)
print(manual_calib)

output:

[(5, 3), (6, 4)]
['grey', 'DarkOrange', 'r', 'black', 'black', 'blue', 'yellow']
['white', 'white', 'white', 'blue', 'yellow', 'blue', 'yellow']

Upvotes: 2

Related Questions