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.
int * ptr = array; std::sort( ptr + 1, ptr + 4 );
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.
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() .
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 isNone
(compare the elements directly).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With