Re[2]: [Tutor] sorting the list

antonmuhin at rambler.ru antonmuhin at rambler.ru" <antonmuhin@rambler.ru
Thu Feb 27 03:57:01 2003


Hello Don,

Wednesday, February 26, 2003, 3:48:18 PM, you wrote:


DA> ----- Original Message -----
DA> From: "siddharth karandikar" <siddharth178@hotmail.com>
DA> To: <tutor@python.org>
DA> Sent: Wednesday, February 26, 2003 6:09 AM
DA> 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 ???
>>

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

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

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

DA> a.sort(mysort)
DA> print a

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


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

DA> a.sort(mysort)
DA> print a

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

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

DA> HTH,
DA> Don

Another solution that can be a little bit quicker for big lists:

>>> a = ['a1', 'a2', 'a3', 'a4', 'a10', 'a11', 'a12']
>>> s = [(e[0], int(e[1:])) for e in a]
>>> print s
[('a', 1), ('a', 2), ('a', 3), ('a', 4), ('a', 10), ('a', 11), ('a', 12)]
>>> s.sort()
>>> print s
[('a', 1), ('a', 2), ('a', 3), ('a', 4), ('a', 10), ('a', 11), ('a', 12)]
>>> new_a = ["%s%s" % e for e in s]
>>> print new_a
['a1', 'a2', 'a3', 'a4', 'a10', 'a11', 'a12']
>>>

Actually, you may consider another presentation for your data too.

-- 
Best regards,
 anton                            mailto:antonmuhin@rambler.ru