Pythonic list reordering

MRAB python at
Sat Apr 10 11:04:26 EDT 2010

alex23 wrote:
> On Apr 9, 8:52 am, Ben Racine <i3enha... at> wrote:
>> 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?
> This approach doesn't rely on knowing the format of the string:
>>>> from string import maketrans, letters, punctuation
>>>> a = ['dir_0_error.dat', 'dir_120_error.dat', 'dir_30_error.dat', 'dir_330_error.dat']
>>>> def only_numbers(s):
> ...     nums = s.translate(None, letters+punctuation)
> ...     return int(nums)
> ...
>>>> a.sort(key=only_numbers)
>>>> a
> ['dir_0_error.dat', 'dir_30_error.dat', 'dir_120_error.dat',
> 'dir_330_error.dat']
> If you're using Python 3.x, the string module has been removed, so you
> can find the maketrans function on str there.

The string module still exists in Python 3.x, but the string functions
which have been superseded by string methods have been removed.

More information about the Python-list mailing list