From: Ben Racine on
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?

Thanks,
Ben R.
From: Chris Rebert on
On Thu, Apr 8, 2010 at 3:52 PM, Ben Racine <i3enhamin(a)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.

a = ['dir_0_error.dat', 'dir_120_error.dat', 'dir_30_error.dat',
'dir_330_error.dat']
def key(item):
return int(item.split('_')[1])
a.sort(key=key)

Cheers,
Chris
--
http://blog.rebertia.com
From: Gary Herron on
Ben Racine 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?
>
> Thanks,
> Ben R.
>

How about a one liner?

L.sort(key=lambda s: int(s.split('_')[1]))


(Which is not necessarily elegant, but it is short.)

Gary Herron

From: Joaquin Abian on
On Apr 9, 12:52 am, Ben Racine <i3enha...(a)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?
>
> Thanks,
> Ben R.

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

joaquin
From: Lie Ryan on
On 04/09/10 08:52, Ben Racine 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?
>
> Thanks,
> Ben R.

list.sort() and sorted() accept `key` argument, which receives a
callable that transform the item to be sorted into sorting key. So if
you have:

l = ['dir_30_error.dat', 'dir_120_error.dat',
'dir_330_error.dat', 'dir_0_error.dat']

# 'dir_0_error.dat' -> 0
# 'dir_30_error.dat' -> 30
def getnum(s):
return int(''.join(x for x in s if x.isdigit()))

# sort based on getnum()'s return value
l.sort(key=getnum)