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

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

    If you wish to sort with different rules for different subgroups you may use tuples as sorting keys. In this case items would be grouped and sorted layer by layer: first by first tuple item, next in each subgroup by second tuple item and so on. This allows us to have different sorting rules in different subgroups. The only limit - items should be comparable within each group. For example, you cannot have int and str type keys in the same subgroup, but you can have them in different subgroups.

    Lets try to apply it to the task. We will prepare tuples with elements types (str, int) for B elements, and tuples with (str, str) for all others.

    def sorter(elem):
        letter, num = elem[0], elem[1:]
        if letter == 'B':
            return letter, int(num or 0)  # hack - if we've got `''` as num, replace it with `0`
        else:
            return letter, num
    
    data = ['A', 'B' , 'B1', 'B11', 'B2', 'B21', 'B22', 'C', 'C1', 'C11', 'C2']
    
    sorted(data, key=sorter)
    # returns
    ['A', 'B', 'B1', 'B2', 'B11', 'B21', 'B22', 'C', 'C1', 'C11', 'C2']
    

    UPDATE

    If you prefer it in one line:

    data = ['A', 'B' , 'B1', 'B11', 'B2', 'B21', 'B22', 'C', 'C1', 'C11', 'C2']
    
    sorted(data, key=lambda elem: (elem[0],  int(elem[1:] or 0) if elem[0]=='B' else elem[:1]
    # result
    ['A', 'B', 'B1', 'B2', 'B11', 'B21', 'B22', 'C', 'C1', 'C2', 'C11']
    

    Anyway these key functions are quite simple, so you can adopt them to real needs.

提交回复
热议问题