recipes.natural_sort

recipes.natural_sort(lst)[source]

Sort a list/NumPy 1darray in a “natural” way

Parameters:

lst : list or NumPy 1darray

Python list or 1darray of strings

Returns:

lst_sort : list or NumPy 1darray

Lexicographically sorted version of the input list lst

See also

None

Notes

This function was originally intended to perform a natural sorting of a file-listing (see Coding Horror’s note on this topic for more details). Briefly, an input list lst of strings containing digits is sorted such that the actual numerical value of the digits is respected (see Examples for more details). The code below is based on a Stackoverflow submission by Mark Byers, currently available here.

Examples

Calling glob in a directory containing files named Elm and elm plus two-digit suffixes will result in a file listing sorted as follows:

>>> lst = ['Elm11', 'Elm12', 'Elm2', 'elm0', 'elm1', 'elm10', 'elm13', 'elm9']

Using natural_sort to order lst yields

>>> natural_sort(lst)
['elm0', 'elm1', 'Elm2', 'elm9', 'elm10', 'Elm11', 'Elm12', 'elm13']