Enforce items at beginning and end of list

后端 未结 8 697
感动是毒
感动是毒 2020-12-14 07:23

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?

8条回答
  •  一整个雨季
    2020-12-14 07:45

    Solution to this question is:

    1. First find all p and q elements in list.
    2. Filter the original list.
    3. Then, finally sort the list.

    list = ['f','g','p','a','p','c','b','q','z','n','d','t','q'];
    noOfPs = [i for i in l if i == 'p']; 
    noOfQs = [i for i in l if i == 'q'];
    resultList= noOfPs + sorted(filter(lambda x:x not in {'q', 'p'}, l))+ noOfQs 
    

提交回复
热议问题