where or filter on list

charles.hebert at gmail.com charles.hebert at gmail.com
Wed Aug 30 08:04:53 EDT 2006


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 ?

Thanks,

CH.




More information about the Python-list mailing list