Enforce items at beginning and end of list

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

    You can use sorted with the following key:

    sorted(l, key = lambda s: (s!='p', s=='q', s))
    ['p', 'p', 'a', 'b', 'c', 'd', 'f', 'g', 'n', 't', 'z', 'q', 'q']
    

    Explanation

    To get a better idea of how this is working, the following list comprehension aims to replicate what is being returned from the lambda function defined in the key argument prior to making comparisons:

    t = [(s!='p', s=='q', s) for s in pl]
    
    print(t)
    [(True, False, 'f'),
     (True, False, 'g'),
     (False, False, 'p'),
     (True, False, 'a'),
     (False, False, 'p'),
     (True, False, 'c'),
     (True, False, 'b'),
     (True, True, 'q'),
     (True, False, 'z'),
     (True, False, 'n'),
     (True, False, 'd'),
     (True, False, 't'),
     (True, True, 'q')]
    

    This will then be the key to be used to sort the items in the list, as mentioned in the documentation:

    The value of the key parameter should be a function that takes a single argument and returns a key to use for sorting purposes.

    So taking into account that False = 0 and True = 1, when this list of tuples is sorted the result will be the following:

    sorted(t)
    [(False, False, 'p'),
     (False, False, 'p'),
     (True, False, 'a'),
     (True, False, 'b'),
     (True, False, 'c'),
     (True, False, 'd'),
     (True, False, 'f'),
     (True, False, 'g'),
     (True, False, 'n'),
     (True, False, 't'),
     (True, False, 'z'),
     (True, True, 'q'),
     (True, True, 'q')]
    

提交回复
热议问题