python 3: sorting with a comparison function

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Thu Oct 9 16:36:58 EDT 2008


Thomas Heller:
> the 'cmp' argument seems to be gone.  Can that be?

Yes, that's a wonderful thing, because from the code I see around
99.9% of people see the cmp and just use it, totally ignoring the
presence of the 'key' argument, that allows better and shorter
solutions of the sorting problem. So removing the cmp is the only way
to rub the nose of programmers on the right solution, and it goes well
with the Python "There should be one-- and preferably only one --
obvious way to do it.".

For most of very uncommon situations where key isn't the right thing,
you can use this code by Hettinger:

def cmp2key(mycmp):
    "Converts a cmp= function into a key= function"
    class K:
        def __init__(self, obj, *args):
            self.obj = obj
        def __cmp__(self, other):
            return mycmp(self.obj, other.obj)
    return K
s.sort(key=cmp2key(lambda p, q: cmp(p.lower(), q.lower())))

That code can't be used in one situation: when the array to be sorted
is huge, that situation can be handled by the original true cmp
function, but not by that cmp2key(). But I have met such situation so
far. When you have an huge amount of data, use an external sort, even
Windows has one, even if its usage is a bit tricky (linux sort command
is safer).

Bye,
bearophile



More information about the Python-list mailing list