sorting a list

Sean Berry sean_berry at cox.net
Wed Apr 28 20:50:27 EDT 2004


>>> a = ['A', 'D', 'F', 'a', 'f']
>>> a.sort(lambda x, y: cmp(string.lower(x), string.lower(y)))
>>> a
['a', 'A', 'D', 'f', 'F']

this will work too, if lower can come before upper.



But Thor
"Thorsten Kampe" <thorsten at thorstenkampe.de> wrote in message
news:17i4tmtsfvae9$.dlg at thorstenkampe.de...
> * ketulp_baroda at yahoo.com (2004-03-10 01:13 +0100)
> > I want to sort a list.
> > My problem is:
> >
> >>>> a=['a','f','F','A','D']
> >>>> a.sort()
> >>>> a
> > ['A','D', 'F', 'a', 'f']
> >
> > But I am actually looking for an output:
> > ['A','a','D','F','f']
> >
> > Is there any module to sort a list this way?
>
> You need a general approach:
>
> def funcsort(seq, func):
>     """ sort seq by func(item) """
>     seq = seq[:]
>     seq.sort(lambda x, y: cmp(func(x), func(y)))
>     return seq
>
> funcsort(a, lambda x: ord(x.upper()) + x.islower()/2.0)
>
>
> Thorsten





More information about the Python-list mailing list