You can use sorted
with the following key
:
sorted(l, key = lambda s: (s!='p', s=='q', s))
['p', 'p', 'a', 'b', 'c', 'd', 'f', 'g', 'n', 't', 'z', 'q', 'q']
Explanation
To get a better idea of how this is working, the following list comprehension aims to replicate what is being returned from the lambda
function defined in the key
argument prior to making comparisons:
t = [(s!='p', s=='q', s) for s in pl]
print(t)
[(True, False, 'f'),
(True, False, 'g'),
(False, False, 'p'),
(True, False, 'a'),
(False, False, 'p'),
(True, False, 'c'),
(True, False, 'b'),
(True, True, 'q'),
(True, False, 'z'),
(True, False, 'n'),
(True, False, 'd'),
(True, False, 't'),
(True, True, 'q')]
This will then be the key
to be used to sort the items in the list, as mentioned in the documentation:
The value of the key parameter should be a function that takes a single argument and returns a key to use for sorting purposes.
So taking into account that False = 0
and True = 1
, when this list of tuples is sorted the result will be the following:
sorted(t)
[(False, False, 'p'),
(False, False, 'p'),
(True, False, 'a'),
(True, False, 'b'),
(True, False, 'c'),
(True, False, 'd'),
(True, False, 'f'),
(True, False, 'g'),
(True, False, 'n'),
(True, False, 't'),
(True, False, 'z'),
(True, True, 'q'),
(True, True, 'q')]