How to sort a list of strings numerically?
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Luau
--
Chapters
00:00 Question
00:57 Accepted answer (Score 220)
01:52 Answer 2 (Score 73)
02:25 Answer 3 (Score 44)
03:00 Answer 4 (Score 32)
03:17 Thank you
--
Full question
https://stackoverflow.com/questions/3426...
Answer 1 links:
[natsort]: https://pypi.org/project/natsort/
Answer 2 links:
[the ]: https://docs.python.org/3/library/stdtyp...
[the ]: http://docs.python.org/library/functions...
Answer 3 links:
[sorted()]: https://docs.python.org/2/library/functi...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #sorting
#avk47
ACCEPTED ANSWER
Score 235
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)
# or if you want to do it all in the same line
list1 = sorted([int(x) for x in list1])
ANSWER 2
Score 48
You could pass a function to the key parameter to the .sort method. With this, the system will sort by int(x) instead of x.
list1.sort(key=int)
BTW, to convert the list to integers permanently, use the map function
list1 = list(map(int, list1)) # you don't need to call list() in Python 2.x
or list comprehension
list1 = [int(x) for x in list1]
ANSWER 3
Score 33
In case you want to use sorted() function: sorted(list1, key=int)
It returns a new sorted list.
ANSWER 4
Score 22
You can also use:
import re
def sort_human(l):
convert = lambda text: float(text) if text.isdigit() else text
alphanum = lambda key: [convert(c) for c in re.split('([-+]?[0-9]*\.?[0-9]*)', key)]
l.sort(key=alphanum)
return l
This is very similar to other stuff that you can find on the internet but also works for alphanumericals like [abc0.1, abc0.2, ...].