sort() comparison lambda for floats/longs

Jack Diederich jack_diederich at email.com
Mon Jul 29 12:44:54 EDT 2002


I had to sort a list of list of floats (Nx2 array)
but I couldn't find a comparison function that would take
a little error delta to do the std C-style comparison

if (a + delta > b && a - delta < b) {
   printf("Yeah, a == b");
}

here is a lambda I am using in a list.sort()
delta_cmp = lambda a,b,delta=0.00001:
  int((((a+delta) > b and (a-delta) < b) and '0') or
      (a > b and 1) or
      (a < b and -1)
      )

The int() is needed to turn the '0' from true into zero
It uses the side effects of 'or' and 'and' to return 0/1/-1

I need the delta because I'm also sorting on the second
column, which could be an int or string, or anything.  If it was just a single list of floats then a compare without
a delta would work because all the nearly-equal values would
still be next to each other.


to sort this
ll = [[1.0, 'A'],
      [2.0, 'B']]

I would do
ll.sort(lambda a,b: delta_cmp(a[0],b[0]) or  cmp(a[1], b[1]))

Is there a better way to do this in python?

thanks in advance, 

-jackdied


-- 
__________________________________________________________
Sign-up for your own FREE Personalized E-mail at Mail.com
http://www.mail.com/?sr=signup

Get 4 DVDs for $.49 cents! plus shipping & processing. Click to join.
http://adfarm.mediaplex.com/ad/ck/990-1736-3566-59





More information about the Python-list mailing list