Enforce items at beginning and end of list

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

    Use the key parameter in sorted:

    l = ['f','g','p','a','p','c','b','q','z','n','d','t','q']
    
    def key(c):
        if c == 'q':
            return (2, c)
        elif c == 'p':
            return (0, c)
        return (1, c)
    
    
    result = sorted(l, key=key)
    print(result)
    

    Output

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

提交回复
热议问题