[FRPythoneers] a more generic sort

jason songhurst jason.songhurst at valtech.com
Tue Jan 21 12:30:33 MST 2003


The optional argument of the sort() method must be either:
  1) a function of exactly two non optional arguments
  2) an object that implements the '__call__(self, [arg]*)' method with
     two non-optional arguments.

Also, the function or function-like object must return a number.  But 
you weren't having problems there...  Yet.

Andrew Diederich wrote:
> def mySort2(a, b, param):
>         return cmp(a[1][param], b[1][param])
> 
> res.sort(mySort2(a, b, 'cn'))

This wrong for a least two reasons.  First, you are calling mySort with 
a non-existent variable.  Second, you are trying to pass the results of 
your sorting function (a number) to the sort() method.  It can't take a 
number, it only takes functions. So we can rule out this approach, even 
without the error.

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

This is wrong for the same reason as the first.  mySort3 takes three 
parameters, and returns a number. So you are passing mySort3() one 
parameter (wrong), and sending (well, trying to send) the numeric result 
to sort() which only takes functions (that's wrong).  So this approach 
is out as well.

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

Again, the function passed to sort() must take exactly two parameters, 
one is no good and three is quite out.

I think Jack already said this, but you could do:

  column = 'cn'
  res.sort(lambda x, y, param=column: cmp(x[1][param], y[1][param]))

which creates an anonymous function of three parameters, and makes the 
third parameter 'p' optional, with a defaults value set to the value of 
the variable 'param'.

or you could try something along the lines of:

  class compareColumn:
     def __init__(self, param):
        self.param = param
     def __call__(self, a, b):
        return cmp(a[1][self.param], b[1][self.param])

  res.sort(compareColumn('cn'))

Which creates an object that looks like a function taking two parameters 
to pass into sort.

Good luck,

Jason Songhurst




More information about the FRPythoneers mailing list