Last active
December 7, 2016 14:53
-
-
Save sloanlance/f64d820729b3b8e646b7e2b3dda6d0d8 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
#!/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) |
See the comments from the article about:
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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)