Force items at beginning and end of list
问题 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'] 回答1: 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,