Created
November 3, 2014 11:06
-
-
Save willcalderbank/84417220798e0e84b409 to your computer and use it in GitHub Desktop.
Human Sort, sorts "something2" before "something10
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import re | |
def tryint(s): | |
try: | |
return int(s) | |
except: | |
return s | |
def alphanum_key(s): | |
""" Turn a string into a list of string and number chunks. | |
"z23a" -> ["z", 23, "a"] | |
""" | |
return [ tryint(c) for c in re.split('([0-9]+)', s) ] | |
def sort_nicely(l): | |
""" Sort the given list in the way that humans expect. | |
""" | |
l.sort(key=alphanum_key) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Taking from http://nedbatchelder.com/blog/200712/human_sorting.html