Nested lambda statements when sorting lists

前端 未结 8 1024
再見小時候
再見小時候 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

    you could convert to integer only if the index of the item is 0 (when reversing the splitted list). The only object (besides the result of split) which is created is the 2-element list used for comparison. The rest are just iterators.

    sorted(lst,key = lambda s : [x if i else int(x) for i,x in enumerate(reversed(s.split("-")))])
    

    As an aside, the - token isn't particularly great when numbers are involved, because it complicates the use of negative numbers (but can be solved with s.split("-",1)

提交回复
热议问题