0

For a list with these strings, I am trying to sort them by the numbers preceding the "_" character.

my_lst = ['25_mg', '2_mg', '200_mg', '10_mg', '5_mg']

Tried several sorts like this one: print(test.sort(key = lambda x: x.split('_')[0]))

But, the list doesn't sort as expected which would be like this:

my_lst = ['2_mg', '5_mg', '10_mg', '25_mg', '200_mg']
1
  • 1
    lambda x: int(x.split('_')[0]) typecast to int. Otherwise it's a string and it's compared character by character lexicographicallly. Commented Apr 24, 2021 at 1:36

1 Answer 1

1

Your sort will order the strings "25", "2", etc, so everything that starts with a "1" will come first. It seems you want to sort by their actual numerical value, so change it to

my_lst.sort(key = lambda x: int(x.split('_')[0]))
print(my_lst)

which gives

['2_mg', '5_mg', '10_mg', '25_mg', '200_mg']
Sign up to request clarification or add additional context in comments.

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.