Force elements at beginning and end of list

  • A+
Category:Languages

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?

l = ['f','g','p','a','p','c','b','q','z','n','d','t','q'] 

So I would like to have:

['p','p','a','b','c','d','f','g','n','t','z','q','q'] 

 


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 called in key 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')] 

So taking into account that False = 0 and True = 1, when this modified list of tuples is sorted the result is:

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

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: