Enforce items at beginning and end of list

后端 未结 8 679
感动是毒
感动是毒 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']
    
    0 讨论(0)
  • 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']
    
    0 讨论(0)
提交回复
热议问题