edesz
edesz

Reputation: 12406

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?

Upvotes: 1

Views: 667

Answers (2)

jimhark
jimhark

Reputation: 5046

I would rewrite what you have to:

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

found = [i for i in main_l if any(e in i for e in hlig)]

Then the solution is obvious:

not_found = [i for i in main_l if not any(e in i for e in hlig)]
answer = not_found + found

EDIT: Removed square brackets around list comprehension based on comments by Sven Marnach (to aviraldg's solution)

Upvotes: 1

aviraldg
aviraldg

Reputation: 9154

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))

Upvotes: 4

Related Questions