Sort a sublist of elements in a list leaving the rest in place

前端 未结 15 2283
小蘑菇
小蘑菇 2021-02-13 14:28

Say I have a sorted list of strings as in:

[\'A\', \'B\' , \'B1\', \'B11\', \'B2\', \'B21\', \'B22\', \'C\', \'C1\', \'C11\', \'C2\']

Now I wan

15条回答
  •  醉酒成梦
    2021-02-13 14:48

    You can use the following key function. It will return a tuple of the form (letter, number) if there is a number, or of the form (letter,) if there is no number. This works since ('A',) < ('A', 1).

    import re
    
    a = ['A', 'B' ,'B1', 'B11', 'B2', 'B21', 'B22', 'C', 'C1', 'C11', 'C2']
    
    regex = re.compile(r'(\d+)')
    
    def order(e):
        num = regex.findall(e)
        if num:
            num = int(num[0])
            return e[0], num
        return e,
    
    print(sorted(a, key=order))
    >> ['A', 'B', 'B1', 'B2', 'B11', 'B21', 'B22', 'C', 'C1', 'C2', 'C11']
    

提交回复
热议问题