Nested lambda statements when sorting lists

前端 未结 8 1036
再見小時候
再見小時候 2020-12-03 21:20

I wish to sort the below list first by the number, then by the text.

lst = [\'b-3\', \'a-2\', \'c-4\', \'d-2\']

# result:
# [\'a-2\', \'d-2\', \'b-3\', \'c-         


        
8条回答
  •  鱼传尺愫
    2020-12-03 22:01

    There are 2 points to note:

    • One-line answers are not necessarily better. Using a named function is likely to make your code easier to read.
    • You are likely not looking for a nested lambda statement, as function composition is not part of the standard library (see Note #1). What you can do easily is have one lambda function return the result of another lambda function.

    Therefore, the correct answer can found in Lambda inside lambda.

    For your specific problem, you can use:

    res = sorted(lst, key=lambda x: (lambda y: (int(y[1]), y[0]))(x.split('-')))
    

    Remember that lambda is just a function. You can call it immediately after defining it, even on the same line.

    Note #1: The 3rd party toolz library does allow composition:

    from toolz import compose
    
    res = sorted(lst, key=compose(lambda x: (int(x[1]), x[0]), lambda x: x.split('-')))
    

    Note #2: As @chepner points out, the deficiency of this solution (repeated function calls) is one of the reasons why PEP-572 is considered implemented in Python 3.8.

提交回复
热议问题