Enforce items at beginning and end of list

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

    You can use the following lambda function as the key in sorted():

    l1 = sorted(l, key=lambda x: ((x == 'q') - (x == 'p'), x))
    
    print(l1)
    # ['p', 'p', 'a', 'b', 'c', 'd', 'f', 'g', 'n', 't', 'z', 'q', 'q']
    

    The function generates the following comparison keys:

    func = lambda x: ((x == 'q') - (x == 'p'), x)
    
    for i in l1:
        print(func(i))
    

    Output:

    (-1, 'p')
    (-1, 'p')
    (0, 'a')
    (0, 'b')
    ...
    (0, 't')
    (0, 'z')
    (1, 'q')
    (1, 'q')
    

提交回复
热议问题