User Tools

Site Tools


notes:python_natural_sort

This is an old revision of the document!


Python Natural Sort

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.1353411306.txt.gz · Last modified: 2012/11/20 11:35 by andy