1

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']
1
  • sort(key=lambda s:int(s[6:])) works as long as the prefix is always 6 characters. Otherwise use itertools.groupby or a regex to separate the numbers from the non-numbers. Commented Sep 13, 2022 at 18:09

3 Answers 3

1

you can use natsort library.

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

output:

['mba23m1', 'mba23m5', 'mba23m23', 'mba23m124']
Sign up to request clarification or add additional context in comments.

Comments

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

you can use following function:

   def f_remove_trailing_digits(s):
           return s.rstrip("0123456789")
  1. Then you can sort using this way

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.