Enforce items at beginning and end of list

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

    One idea is to use a priority dictionary with a custom function. This is naturally extendable should you wish to include additional criteria.

    L = ['f','g','p','a','p','c','b','q','z','n','d','t','q']
    
    def sort_func(x):
        priority = {'p': 0, 'q': 2}
        return priority.get(x, 1), x
    
    res = sorted(L, key=sort_func)
    
    print(res)
    
    ['p', 'p', 'a', 'b', 'c', 'd', 'f', 'g', 'n', 't', 'z', 'q', 'q']
    

提交回复
热议问题