[FRPythoneers] a more generic sort

Andrew Diederich diederic at boulder.net
Tue Jan 21 10:49:06 MST 2003


when we last met, I'd settled on  a custom sort on 'cn' like this:

> def mySort(a, b):
>       return cmp(a[1]['cn'], b[1]['cn'])
> res.sort(mySort)

One of the things I've thought about doing is making the columns
individualy sortable, so if you wanted to sort by phone number, you could
do that.

So instead of making four different sort algorithms (for cn,
telephoneNumber, mail, and title) I was wondering if there was a way to
pass a third argument into mySort for the ldap tag.  I checked both of my
Lutz books, and didn't find a good answer.

What I've tried:
def mySort2(a, b, param):
        return cmp(a[1][param], b[1][param])

res.sort(mySort2(a, b, 'cn'))

Traceback (innermost last):
  File "./phonebook.py", line 34, in ?
    res.sort(mySort2(a, b, 'cn'))
NameError: a

def mySort3(a, b, param):
        return cmp(a[1][param], b[1][param])


Traceback (innermost last):
  File "./phonebook.py", line 34, in ?
TypeError: not enough arguments; expected 3, got 1

is this even possible?  p. 1020 of Programming Python has a neat example
with a lambda, but I don't see how I'd pass in the value into a lambda.

res.sort( lambda x, y, param: cmp(x[param], y[param]) )

The book example does essentially this:
res.sort( lambda x, y: cmp(x['cn'], y['cn']) )

and maybe that's as easy as it's going to get for what I want.

Thanks in advance,

Andrew Diederich

More information about the FRPythoneers mailing list