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

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

    import numpy as np
    
    def sort_with_prefix(list, prefix):
        alist = np.array(list)
        ix = np.where([l.startswith(prefix) for l in list])
    
        alist[ix] =  [prefix + str(n or '')
                 for n in np.sort([int(l.split(prefix)[-1] or 0) 
                                  for l in alist[ix]])]
        return alist.tolist()
    

    For example:

    l = ['A', 'B', 'B1', 'B2', 'B11', 'B21', 'B22', 'C', 'C1', 'C2', 'C11']
    
    print(sort_with_prefix(l, 'B'))
    >> ['A', 'B', 'B1', 'B2', 'B11', 'B21', 'B22', 'C', 'C1', 'C11', 'C2']
    

提交回复
热议问题