Skip to content

Instantly share code, notes, and snippets.

@edthrn
Last active August 16, 2019 15:57
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save edthrn/5e23e494f5cfbd94cf5e19201d63ccaa to your computer and use it in GitHub Desktop.
Sorting for humans with Python
# 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