Last active
August 16, 2019 15:57
-
-
Save edthrn/5e23e494f5cfbd94cf5e19201d63ccaa to your computer and use it in GitHub Desktop.
Sorting for humans with Python
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 https://blog.codinghorror.com/sorting-for-humans-natural-sort-order/ | |
# Adding a `key` argument so we can expect the same behaviour as the builtin `sorted` | |
import re | |
def humansorted(seq, key=None): | |
"""Return the sequence in the order that a human being expects. | |
If `key` is provided, as per the built-in `sorted` function, it must be a | |
callable that accepts a single argument. | |
>>> unsorted_list = ['zip2', 'zip1', 'zip10'] | |
>>> sorted(unsorted_list) | |
'zip1', 'zip10', 'zip2' | |
>>> humansorted(unsorted_list) | |
'zip1', 'zip2', 'zip10' | |
""" | |
def convert(text): | |
return int(text) if text.isdigit() else text | |
def alphanum(obj): | |
if key is not None: | |
return [convert(c) for c in re.split(r'([0-9]+)', key(obj))] | |
return [convert(c) for c in re.split(r'([0-9]+)', obj)] | |
return sorted(seq, key=alphanum) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment