sorting a list

Karl Pflästerer sigurd at 12move.de
Tue Mar 9 19:06:04 EST 2004


An unnamed person wrote:

> 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 don't need a module.  The sorting method can take a custom sorting
function.

>>> L = ['a','f','F','A','D']
>>> L.sort(lambda u, v: cmp(u.lower(), v.lower()) or cmp(u, v))
>>> L
['A', 'a', 'D', 'F', 'f']
>>> 

As 0 is the same as a boolean false value the comparing function will
try the part after the `or' if two values were equal compared with
`cmp(u.lower(), v.lower())' to ensure `A' comes before `a'.



   KP

-- 
"Programs must be written for people to read, and only incidentally
for machines to execute."
                -- Abelson & Sussman, SICP (preface to the first edition)



More information about the Python-list mailing list