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)
--
http://mail.python.org/mailman/listinfo/python-list