Need Help sorting alphabetically.

Remco Gerlich scarblac at pino.selwerd.nl
Tue Dec 19 04:01:39 EST 2000


Chris Arai <chris at araidesign.com> wrote in comp.lang.python:
> This seems like it should be obvious, but it is evading me!
> 
> I would like to sort alphabetically (I'm not sure that is the correct
> term) so that strings of alpha numerics sort alphabetically instead of
> by ASCII order.
> 
> eg:
> >>> m=['Pg95_100.GIF',
> 'Pg9_100.GIF','Pg95A_100.gif','Pg9A_100.gif','Pg10_100.gif']
> >>> m.sort()
> >>> m
> ['Pg10_100.gif', 'Pg95A_100.gif', 'Pg95_100.GIF', 'Pg9A_100.gif',
> 'Pg9_100.GIF']
> 
> 
> I would like the order to be
> ['Pg9_100.GIF', 'Pg9A_100.gif', 'Pg10_100.gif, 'Pg95_100.GIF',
> Pg95A_100.gif' ]
> 
> What is the obvious answer??

It seems you want to ignore case and ignore everything outside a-z.
So make a function that throws out all of the other characters and
turns the rest into a single case, and then compares those:

def compare_alphabetically(a, b):
   a = filter(lambda x: x.isalpha(), a.upper())
   b = filter(lambda x: x.isalpha(), b.upper())
   return cmp(a,b)

And use that to sort the list

m.sort(compare_alphabetically)

In older versions without string methods those lines should read
   import string
   a = filter(lambda x: 'A' <= x <= 'Z', string.upper(a))
   (etc)

-- 
Remco Gerlich



More information about the Python-list mailing list