W R W R - 1 year ago 98
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
to the end of the list if they contain strings listed in

Final version of
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
contains elements with a substring listed in the 2nd list
. Here is the way I am doing this:

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

is a sublist of
. 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
. If I could do this, then I could add them to a list
and then I could concatenate them like this:
not_found + found
- and this would give me what I want.


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

Answer Source

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))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download