Home > Mobile >  How to convert whole list of string into integer using python
How to convert whole list of string into integer using python

Time:05-27

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]

CodePudding user response:

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

CodePudding user response:

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