How to sort a list of strings numerically?
I approached the same problem yesterday and found a module called natsort, which solves your problem. Use:
from natsort import natsorted # pip install natsort
# Example list of strings
a = ['1', '10', '2', '3', '11']
[In] sorted(a)
[Out] ['1', '10', '11', '2', '3']
[In] natsorted(a)
[Out] ['1', '2', '3', '10', '11']
# Your array may contain strings
[In] natsorted(['string11', 'string3', 'string1', 'string10', 'string100'])
[Out] ['string1', 'string3', 'string10', 'string11', 'string100']
It also works for dictionaries as an equivalent of sorted
.
You haven't actually converted your strings to ints. Or rather, you did, but then you didn't do anything with the results. What you want is:
list1 = ["1","10","3","22","23","4","2","200"]
list1 = [int(x) for x in list1]
list1.sort()
If for some reason you need to keep strings instead of ints (usually a bad idea, but maybe you need to preserve leading zeros or something), you can use a key function. sort
takes a named parameter, key
, which is a function that is called on each element before it is compared. The key function's return values are compared instead of comparing the list elements directly:
list1 = ["1","10","3","22","23","4","2","200"]
# call int(x) on each element before comparing it
list1.sort(key=int)