Enforce items at beginning and end of list

后端 未结 8 696
感动是毒
感动是毒 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:54

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

提交回复
热议问题