[EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > Can anybody tell me how to to find the nearest value to zero in a > list?
> >>> 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 ? Maybe something like this: mindist = min(map(abs, foo)) filter(lambda x: abs(x) == mindist, a)[0] Only annoyance: we compute abs twice for each value. We could probably avoid that by using reduce() and a suitable function... > How to extend this function to any given value ? By subtracting the desired value from foo. cu Philipp -- Dr. Philipp Pagel Tel. +49-8161-71 2131 Dept. of Genome Oriented Bioinformatics Fax. +49-8161-71 2186 Technical University of Munich http://mips.gsf.de/staff/pagel -- http://mail.python.org/mailman/listinfo/python-list