sorting a list

Delaney, Timothy C (Timothy) tdelaney at avaya.com
Tue Mar 9 18:25:39 EST 2004


> From: ketulp_baroda at yahoo.com
> 
> Hi
> 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?

Many. However, first you need to clarify a few things.

1. Do you want to sort completely case-insensitively, or do you specifically want to sort uppercase before lowercase for the same letter.

2. Is your input restricted to ASCII? Once you start getting into Unicode things become more difficult.

Anyway, the two major methods are to pass a `cmp` function, or to perform decorate-sort-undecorate.

    # Pass a comparison function.
    a.sort(cmp=func)

    # DSU
    a = [(key_func(x), x) for x in a]
    a.sort()
    a = [x[-1] for x in a]

DSU will almost always be faster. Note also that in Python 2.4 there will be built-in support for DSU via the `key` parameter to `sort`:

    a.sort(key=key_func)

except that it doesn't actually need to undecorate, so it's even faster.

Tim Delaney




More information about the Python-list mailing list