On Apr 9, 1:58 am, Chris Rebert <c...@rebertia.com> wrote: > On Thu, Apr 8, 2010 at 4:01 PM, Joaquin Abian <gatoyga...@gmail.com> wrote: > > On Apr 9, 12:52 am, Ben Racine <i3enha...@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 -- http://mail.python.org/mailman/listinfo/python-list