Created
February 10, 2012 08:54
-
-
Save signed0/1787885 to your computer and use it in GitHub Desktop.
Python natural sort key
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
# Inspired by http://code.activestate.com/recipes/285264-natural-string-sorting/ | |
import re | |
digits = re.compile(r'(\d+|\D+)') | |
def natural_sort_key(item): | |
if item is None or item == '': | |
return None | |
pieces = digits.findall(item) | |
pieces = (int(i) if i.isdigit() else i for i in pieces) | |
return tuple(pieces) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment