Sorting a list of strings with a specific method

后端 未结 2 1352
小鲜肉
小鲜肉 2021-01-22 16:22

let\'s say i have a list of strings like this

L = [\'5\', \'3\', \'4\', \'1\', \'2\', \'2 3 5\', \'2 4 8\', \'5 22 1 37\', \'5 22 1 22\', \'5 22 1 23\', ....]


        
相关标签:
2条回答
  • 2021-01-22 16:51

    You could sort using a tuple:

    L = ['5', '3', '4', '1', '2', '2 3 5', '2 4 8', '5 22 1 37', '5 22 1 22', '5 22 1 23']
    
    result = sorted(L, key=lambda x: (len(x.split()),) + tuple(map(int, x.split())))
    
    print(result)
    

    Output

    ['1', '2', '3', '4', '5', '2 3 5', '2 4 8', '5 22 1 22', '5 22 1 23', '5 22 1 37']
    

    The idea is to use as key a tuple where the first element is the amount of numbers in the string and the rest is the tuple of numbers. For example for '2 3 5' the key is (3, 2, 3, 5)

    As suggested by @PM2Ring you could use a def function instead of a lambda:

    def key(x):
        numbers = tuple(map(int, x.split()))
        return (len(numbers),) + numbers
    
    0 讨论(0)
  • 2021-01-22 16:56

    A slightly different approach than @Daniel's one.

    idx = sorted(range(len(L)), key=lambda i: int(''.join(L[i].split())))
    L = [L[i] for i in idx]
    

    output

    ['1',
     '2',
     '3',
     '4',
     '5',
     '2 3 5',
     '2 4 8',
     '5 22 1 22',
     '5 22 1 23',
     '5 22 1 37']
    
    0 讨论(0)
提交回复
热议问题