How can I modify this list so that all p\'s
appear at the beginning, the q\'s
at the end, and the values in between are sorted alphabetically?
Use the key
parameter in sorted:
l = ['f','g','p','a','p','c','b','q','z','n','d','t','q']
def key(c):
if c == 'q':
return (2, c)
elif c == 'p':
return (0, c)
return (1, c)
result = sorted(l, key=key)
print(result)
Output
['p', 'p', 'a', 'b', 'c', 'd', 'f', 'g', 'n', 't', 'z', 'q', 'q']
You can find all p
and q
elements, filter the original list, and then sort:
l = ['f','g','p','a','p','c','b','q','z','n','d','t','q']
_ps, _qs = [i for i in l if i == 'p'], [i for i in l if i == 'q']
new_l = _ps+sorted(filter(lambda x:x not in {'q', 'p'}, l))+_qs
Output:
['p', 'p', 'a', 'b', 'c', 'd', 'f', 'g', 'n', 't', 'z', 'q', 'q']