0

Having list like l1=['abc.123','abc.456','abc.789','abc.153'] I want to sort this list based on numbers which are suffixes. But for that reason I have to convert this string list into integer. How can we do that.

Desired output is : l1= [abc.123,abc.153,abc.456,abc.789]

3
  • Please provide enough code so others can better understand or reproduce the problem. Commented May 27, 2022 at 4:54
  • sorted(my_lst, key = lambda x: x[-3:]) or even sorted(my_lst, key = lambda x: int(x[-3:])) Commented May 27, 2022 at 4:55
  • Does this answer your question? Sort list of strings by a part of the string Commented May 27, 2022 at 5:13

2 Answers 2

1

The safest way is to sort on the integer value of the part after the period, not of the last three characters. This allows for strings with fewer or more digits.

sorted(my_lst, key = lambda x: int(x.split(".")[-1]))
Sign up to request clarification or add additional context in comments.

Comments

0

If we know that the last 3 characters are digits we could do:

sorted(my_lst, key = lambda x: int(x[-3:]))
['abc.123', 'abc.153', 'abc.456', 'abc.789']

or even noting that the are 3 numeric characters, you can go ahead and use them:

sorted(my_lst, key = lambda x: x[-3:])
['abc.123', 'abc.153', 'abc.456', 'abc.789']

4 Comments

But this is not good practice to sort string based on the numbers because sort will not treat number as a digit it will treat them as a string so thats the reason first convert it into integer and the sort them .
@rrr. Look at my assumption. I am taking only the last 3 digits. Whether sorted as string/integer will be the same. Eg '000' is the smallest while '999' is the largest.
so I have to split the list
@rrr check the answe given below

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.