User Tools

Site Tools


notes:python_natural_sort

Python Natural Sort

naturalsort.py
import re
 
NATURAL_SORT_RE = re.compile('([0-9]+)')
 
def natural_sorted(to_sort, reverse=False):
    convert = lambda text: int(text) if text.isdigit() else text
    alphanum_key = lambda key: [convert(c) for c in NATURAL_SORT_RE.split(key)]
    return sorted(to_sort, key=alphanum_key, reverse=reverse)
notes/python_natural_sort.txt · Last modified: 2012/11/20 11:46 by andy