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

前端 未结 15 2259
小蘑菇
小蘑菇 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:44

    To answer precisely what you describe you can do this :

    l = ['A', 'B' , 'B1', 'B11', 'B2', 'B21', 'B22', 'C', 'C1', 'C11', 'C2', 'D']
    
    
    def custom_sort(data, c):
        s = next(i for i, x in enumerate(data) if x.startswith(c))
        e = next((i for i, x in enumerate(data) if not x.startswith(c) and i > s), -1)
        return data[:s] + sorted(data[s:e], key=lambda d: int(d[1:] or -1)) + data[e:]
    
    
    print(custom_sort(l, "B"))
    

    if you what an complete sort you can simply do this (as @Mike JS Choi answered but simplier) :

    output = sorted(l, key=lambda elem: (elem[0], int(elem[1:] or -1)))
    

提交回复
热议问题