Pythonic list reordering

Kent Engström kent at lysator.liu.se
Sat Apr 10 07:31:35 EDT 2010


Ben Racine <i3enhamin at gmail.com> writes:
> I have a list...
>
> ['dir_0_error.dat', 'dir_120_error.dat', 'dir_30_error.dat', 'dir_330_error.dat']
>
> I want to sort it based upon the numerical value only.
>
> Does someone have an elegant solution to this? 

I use code like the hack below to sort miscellaneous strings that
consist of mixed numerical and non-numerical parts.

import re

nsk_re = re.compile("([0-9]+)|([^0-9]+)")
def numeric_sort_key(x):
    return [handle_int_nonint(i_ni) for i_ni in nsk_re.findall(x)]

def handle_int_nonint(int_nonint_tuple):
    if int_nonint_tuple[0]:
        return int(int_nonint_tuple[0])
    else:
        return int_nonint_tuple[1]

def numerically_sorted(l):
    return sorted(l, key=numeric_sort_key)




More information about the Python-list mailing list