Pythonic list reordering

alex23 wuwei23 at
Sat Apr 10 10:51:30 EDT 2010

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',

If you're using Python 3.x, the string module has been removed, so you
can find the maketrans function on str there.

More information about the Python-list mailing list