[Tutor] sorting the list

Don Arnold Don Arnold" <darnold02@sprynet.com
Wed Feb 26 07:50:27 2003


----- Original Message -----
From: "siddharth karandikar" <siddharth178@hotmail.com>
To: <tutor@python.org>
Sent: Wednesday, February 26, 2003 6:09 AM
Subject: [Tutor] sorting the list


>
>
> i have list like this
> >>>a = ['a1', 'a2', 'a3', 'a4', 'a10', 'a11', 'a12']
> >>>a
> ['a1', 'a2', 'a3', 'a4', 'a10', 'a11', 'a12']
>
> when i call
> >>>a.sort()
>
> list becomes
> >>>a
> ['a1', 'a10', 'a11', 'a12', 'a2', 'a3', 'a4']
> **# here a10 is getting ahead of a2 a3 etc
> >>>
>
> but i need the list to be sorted like
>
> a1 a2 a3 a4 ... a10 a11 etc.
>
>
> any possible solution ???
>

This is a little simplistic, but I think this works. It requires that each
string has 1 or more numeric characters after the first one.

def mysort(lhs, rhs):
    if rhs[0] <> lhs[0]:
        return cmp(lhs[0],rhs[0])
    else:
        return cmp(int(lhs[1:]),int(rhs[1:]))

a = ['a11','a10','a9','a8','a7','a6','a5','a4','a3','a2','a1']

a.sort(mysort)
print a

>>>> ['a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9', 'a10', 'a11']


a = ['b11','a10','b9','a8','b7','a6','b5','a4','b3','a2','b1']

a.sort(mysort)
print a

>>>>['a2', 'a4', 'a6', 'a8', 'a10', 'b1', 'b3', 'b5', 'b7', 'b9', 'b11']

Note that this sort will consider 'a07' == 'a7'. Not sure if that's a
problem for you or not.

HTH,
Don