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-
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)