Nested lambda statements when sorting lists

前端 未结 8 1018
再見小時候
再見小時候 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:05
    lst = ['b-3', 'a-2', 'c-4', 'd-2']
    res = sorted(lst, key=lambda x: tuple(f(a) for f, a in zip((int, str), reversed(x.split('-')))))
    print(res)
    
    ['a-2', 'd-2', 'b-3', 'c-4']
    
    0 讨论(0)
  • 2020-12-03 22:08

    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']
    
    0 讨论(0)
提交回复
热议问题