Home > front end >  How to sort python list by numbers? [duplicate]
How to sort python list by numbers? [duplicate]

Time:09-17

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?

CodePudding user response:

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']
>>> 

CodePudding user response:

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']

CodePudding user response:

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

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