Skip to content

Instantly share code, notes, and snippets.

@willcalderbank
Created November 3, 2014 11:06
Show Gist options
  • Save willcalderbank/84417220798e0e84b409 to your computer and use it in GitHub Desktop.
Save willcalderbank/84417220798e0e84b409 to your computer and use it in GitHub Desktop.
Human Sort, sorts "something2" before "something10
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)
@willcalderbank
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment