Nested lambda statements when sorting lists

前端 未结 8 1019
再見小時候
再見小時候 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 21:54

    I think* if you are certain the format is consistently "[0]alphabet [1]dash" following indexes beyond [2:] will always be number, then you can replace split with slice, or you can use str.index('-')

    sorted(lst, key=lambda x:(int(x[2:]),x[0]))
    
    # str.index('-') 
    sorted(lst, key=lambda x:(int(x[x.index('-')+1 :]),x[0])) 
    

提交回复
热议问题