On 2006-08-30, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > Hi, > > Can anybody tell me how to to find the nearest value to zero in a list > ? > > To do that, i'm using list comprenhension : > >>>> foo = [-5,-1,2,3] # nearest value to zero ? >>>> [value for value in foo if math.fabs(value) == min([int(math.fabs(x)) for >>>> x in foo])] > [-1] > > Something simpler ? > How to extend this function to any given value ?
A hand-crafted loop seems like an efficient solution: def closest_to(n, seq): m = 0 for i in xrange(1, len(seq)): if abs(n-seq[i]) < abs(n-seq[m]): m = i return seq[m] Putting my faith in Python builtins instead: def closest_to(n, seq): s = [abs(n-x) for x in seq] return seq[s.index(min(s))] -- Neil Cerutti -- http://mail.python.org/mailman/listinfo/python-list