Pythonic list reordering

Joaquin Abian gatoygata2 at gmail.com
Fri Apr 9 09:21:26 EDT 2010


On Apr 9, 1:58 am, Chris Rebert <c... at rebertia.com> wrote:
> On Thu, Apr 8, 2010 at 4:01 PM, Joaquin Abian <gatoyga... at gmail.com> wrote:
> > On Apr 9, 12:52 am, Ben Racine <i3enha... at gmail.com> 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?
>
> > not sure about elegance, but my two cents:
>
> >>> mylist = ['dir_0_error.dat', 'dir_120_error.dat', 'dir_30_error.dat', 'dir_330_error.dat']
> >>> mylist = [(int(item.split('_')[1]), item) for item in mylist]
> >>> mylist.sort()
> >>> mylist = [item for idx, item in mylist]
> >>> mylist
>
> > ['dir_0_error.dat', 'dir_30_error.dat', 'dir_120_error.dat',
> > 'dir_330_error.dat']
>
> At least conceptually, that's how list.sort() with a key= argument
> works internally (i.e. via Schwartzian transform).
>
> Cheers,
> Chris
> --http://blog.rebertia.com

Chris, thanks for the comment. I did not know that name (Schwartzian
transform)
I knew it as the decorate-sort-undecorate strategy.
Now after learning that it was a Perl idiom I feel somewhat
embarrassed ;-)

BTW, I actually prefer the l.sort(key=f) method.
Just my lazy neurons were back to Python 2.3 when I wrote the
response.

Joaquin




More information about the Python-list mailing list