where or filter on list
Philipp Pagel
pDOTpagel at gsf.de
Wed Aug 30 09:06:34 EDT 2006
charles.hebert at gmail.com <charles.hebert at gmail.com> 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
More information about the Python-list
mailing list