Nested lambda statements when sorting lists
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 onelambda
function return the result of anotherlambda
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.
We can wrap the list returned by split('-')
under another list and then we can use a loop to handle it:
# Using list-comprehension
>>> sorted(lst, key=lambda x: [(int(num), text) for text, num in [x.split('-')]])
['a-2', 'd-2', 'b-3', 'c-4']
# Using next()
>>> sorted(lst, key=lambda x: next((int(num), text) for text, num in [x.split('-')]))
['a-2', 'd-2', 'b-3', 'c-4']