I am trying to sort list of strings containing numbers
a = ["1099.0","9049.0"] a.sort() a ['1099.0', '9049.0'] b = ["949.0","1099.0"] b.sort() b ['1099.0', '949.0'] a ['1099.0', '9049.0']
But list b is sorting and not list a
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You want to sort based on the float values (not string values), so try:
>>> b = ["949.0","1099.0"] >>> b.sort(key=float) >>> b ['949.0', '1099.0']
Method 2
use a lambda inside sort to convert them to float and then sort properly:
a = sorted(a, key=lambda x: float(x))
so you will mantain them as strings but sorted by value and not lexicographically
Method 3
In case anybody is dealing with numbers and extensions such as 0.png, 1.png, 10.png, 2.png…
We need to retrieve and sort the characters before the extension since this extension does not let us to convert the names to floats:
myList = sorted(myList, key=lambda x: float(x[:-4]))
Method 4
Convert them to int or float or even decimal (since it has trailing numbers)
>>> b = [float(x) for x in b] >>> b.sort() >>> b [949.0, 1099.0]
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0