Skip to content

Instantly share code, notes, and snippets.

@sloanlance
Last active December 7, 2016 14:53
Show Gist options
  • Save sloanlance/f64d820729b3b8e646b7e2b3dda6d0d8 to your computer and use it in GitHub Desktop.
Save sloanlance/f64d820729b3b8e646b7e2b3dda6d0d8 to your computer and use it in GitHub Desktop.
#!/usr/bin/python
# -*- coding: utf-8 -*-
# From http://nedbatchelder.com/blog/200712/human_sorting.html
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)
@sloanlance
Copy link
Author

Formatted with http://www.tutorialspoint.com/online_python_formatter.htm

I wonder whether performance would improve if the regular expression were precompiled and reused.

Compare to Dave Koelle's Alphanum algorithm (If the site is down, use the archive.org copy)

@sloanlance
Copy link
Author

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