Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a list of string in python such that a specific string, if present appears first

I am new to python and hoping that someone can help me out with this. I need to sort a list of strings :

s = ['status', 'value', 'place', 'tag']

I need to sort in such a way that the sorted list looks like this :

s_sorted = ['tag', 'place', 'status', 'value']

In order words, the specific string 'tag' needs to be always in front and the rest of the strings are going to be sorted. I was trying to come up with a comparator that will allow me to do so. But I haven't been able to do that so far. If anyone has experience solving problem like this, I would appreciate if you can share some thoughts.

like image 303
Santanu C Avatar asked Apr 15 '14 17:04

Santanu C


People also ask

How do I sort a specific part of a list in Python?

int * ptr = array; std::sort( ptr + 1, ptr + 4 );

Can you sort a list of strings Python?

Custom Sorting With key= For example with a list of strings, specifying key=len (the built in len() function) sorts the strings by length, from shortest to longest. The sort calls len() for each string to get the list of proxy length values, and then sorts with those proxy values.

How do you sort items in a string in Python?

In Python, there are two ways, sort() and sorted() , to sort lists ( list ) in ascending or descending order. If you want to sort strings ( str ) or tuples ( tuple ), use sorted() .


1 Answers

s = ['status', 'value', 'place', 'tag']
s_sorted = sorted(s, key=lambda x:(x!='tag', x))

The key generates a tuple, with first element boolean of if the element isn't 'tag'. sort sorts by the first element, then the second. This way tag always comes first because False sorts before True.

In the case of the remaining elements - not equal to 'tag' - sorting is done normally on the second tuple element, which is a lexicographical string sort on the value itself.


From the sorted documentation:

key specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower. The default value is None (compare the elements directly).

like image 85
mhlester Avatar answered Oct 15 '22 09:10

mhlester