Sorting a list of strings with a specific method

后端 未结 2 1354
小鲜肉
小鲜肉 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
    

提交回复
热议问题