W R W R - 2 months ago 8
Python Question

Python move multiple elements (based on criteria) to end of list

I have the following 2 Python lists:

main_l = ['Temp_Farh', 'Surface', 'Heater_back', 'Front_Press',
'Lateral_Cels', 'Gauge_Finl','Gauge_Relay','Temp_Throw','Front_JL']
hlig = ['Temp', 'Lateral', 'Heater','Front']


I need to move elements from
main_l
to the end of the list if they contain strings listed in
hlig
.

Final version of
main_l
should look like this:

main_l = ['Surface', 'Gauge_Finl','Gauge_Relay', 'Temp_Farh', 'Heater_back', 'Front_Press',
'Lateral_Cels', 'Temp_Throw','Front_JL']


My attempt:

I first try to find if the list
main_l
contains elements with a substring listed in the 2nd list
hlig
. Here is the way I am doing this:

`found` = [i for e in hlig for i in main_l if e in i]


found
is a sublist of
main_l
. The problem is: now that I have this list, I do not know how to select the elements that do NOT contain the substrings in
hlig
. If I could do this, then I could add them to a list
not_found
and then I could concatenate them like this:
not_found + found
- and this would give me what I want.

Question:

Is there a way to move matching elements to end of the list
main_l
?

Answer

You could sort main_l using whether each element contains a string from hlig as a key:

main_l.sort(key=lambda x: any(term in x for term in hlig))