Home > Blockchain >  Python: How to sort strings with regards to their trailing numbers?
Python: How to sort strings with regards to their trailing numbers?

Time:09-14

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

CodePudding user response:

you can use natsort library.

from natsort import natsorted # pip install natsort
list = ['mba23m23', 'mba23m124', 'mba23m1', 'mba23m5']

output:

['mba23m1', 'mba23m5', 'mba23m23', 'mba23m124']

CodePudding user response:

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

CodePudding user response:

  1. Create a function to remove trailing digits and return other part of the string. (Lets consider this function as f_remove_trailing_digits(s) )

    def f_remove_trailing_digits(s): return s.rstrip("0123456789")

  2. Then you can sort using this way

    list.sort(key=lambda x:f_remove_trailing_digits(x))

  • Related