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

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

    You can use ord() to transform for exemple 'B11' in numerical value:

    cells = ['B11', 'C1', 'A', 'B1', 'B2', 'B21', 'B22', 'C11', 'C2', 'B']
    conv_cells = []
    
    ## Transform expression in numerical value.
    for x, cell in enumerate(cells):
        val = ord(cell[0]) * (ord(cell[0]) - 65) ## Add weight to ensure respect order.
        if len(cell) > 1:
            val += int(cell[1:])
        conv_cells.append((val, x)) ## List of tuple (num_val, index).
    
    ## Display result.
    for x in sorted(conv_cells):
        print(str(cells[x[1]]) + ' - ' + str(x[0]))
    

提交回复
热议问题