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-4']
Attempt 1
res = sorted(lst, key=lambda x: (int(x.split('-')[1]), x.split('-')[0]))
I was not happy with this since it required splitting a string twice, to extract the relevant components.
Attempt 2
I came up with the below solution. But I am hoping there is a more succinct solution via Pythonic lambda
statements.
def sorter_func(x):
text, num = x.split('-')
return int(num), text
res = sorted(lst, key=sorter_func)
I looked at Understanding nested lambda function behaviour in python but couldn't adapt this solution directly. Is there a more succinct way to rewrite the above code?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…