0

I would like to sort the following list by numbers :

x = ('a-34','a-1','a-0', 'a-11', 'a-2')
y = sorted(x)
print(y)

This produces : ['a-0', 'a-1', 'a-11', 'a-2', 'a-34']

But I need : ['a-0', 'a-1', 'a-2', 'a-11', 'a-34'] How can I do this?

Sofia
  • 21
  • 5
  • 2
    Does this answer your question? [Sort list of strings by integer suffix](https://stackoverflow.com/questions/4287209/sort-list-of-strings-by-integer-suffix) – blhsing Aug 30 '21 at 06:57
  • 1
    Does this answer your question? [Sort list of strings by integer suffix](https://stackoverflow.com/questions/4287209/sort-list-of-strings-by-integer-suffix) – I'mahdi Aug 30 '21 at 08:31
  • Oops; somehow [Sort list of strings by integer suffix](https://stackoverflow.com/questions/4287209/sort-list-of-strings-by-integer-suffix) didn't make it into the list of duplicates when the question was closed. – Stef Aug 30 '21 at 12:38

3 Answers3

4

Try using sorted with the key argument:

>>> sorted(a, key=lambda x: int(x.split('-')[-1]))
['a-0', 'a-1', 'a-2', 'a-11', 'a-34']
>>> 

Or indexing with find:

>>> sorted(a, key=lambda x: int(x[x.find('-') + 1:]))
['a-0', 'a-1', 'a-2', 'a-11', 'a-34']
>>> 
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
0

This can be done easily using the key parameter in the sorted() function

>>> sorted(a, key = lambda x: x.split('-')[-1])
['a-0', 'a-1', 'a-11', 'a-2', 'a-34']
0

Use the key argument in sorted method and provide a lambda function to it.

sorted(a, key = lambda x: int(x.split("-")[-1]))
theunknownSAI
  • 300
  • 1
  • 4