Reputation: 13
What is the best way to sort a list of strings with trailing digits
>>> list = ['mba23m23', 'mba23m124', 'mba23m1', 'mba23m5']
>>> list.sort()
>>> print list
['mba23m1', 'mba23m124', 'mba23m23', 'mba23m5']
is there a way to have them sorted as
['mba23m1', 'mba23m5', 'mba23m23', 'mba23m124']
Upvotes: 1
Views: 229
Reputation: 1202
you can use following function:
def f_remove_trailing_digits(s):
return s.rstrip("0123456789")
Then you can sort using this way
list.sort(key=lambda x:f_remove_trailing_digits(x))
Upvotes: 1
Reputation: 83
you can use natsort library.
from natsort import natsorted # pip install natsort
list = ['mba23m23', 'mba23m124', 'mba23m1', 'mba23m5']
output:
['mba23m1', 'mba23m5', 'mba23m23', 'mba23m124']
Upvotes: 1
Reputation: 10102
Use a lambda (anonymous) function and sort()
's key
argument:
ls = ['mba23m23', 'mba23m124', 'mba23m1', 'mba23m5']
ls.sort(key=lambda x: int(x.split('m')[-1]))
print(ls)
Yielding:
['mba23m1', 'mba23m5', 'mba23m23', 'mba23m124']
Upvotes: 0