Need Help sorting alphabetically.
Greg Jorgensen
gregj at pobox.com
Wed Dec 20 01:30:06 EST 2000
"Remco Gerlich" <scarblac at pino.selwerd.nl> wrote in message
news:slrn93u8qc.5lh.scarblac at pino.selwerd.nl...
> Chris Arai <chris at araidesign.com> wrote in comp.lang.python:
> > 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.
[snip]
> 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)
The filter is unnecessary; the upper() and lower() methods of string only
change alphabetic characters. A simpler solution is:
def compare_alpha(a, b):
return cmp(a.lower(), b.lower())
...
m.sort(compare_alpha)
or use a lambda:
m.sort(lambda a,b: cmp(a.lower(), b.lower()))
--
Greg Jorgensen
Deschooling Society
Portland, Oregon, USA
gregj at pobox.com
More information about the Python-list
mailing list