where or filter on list
Larry Bates
larry.bates at websafe.com
Wed Aug 30 09:09:12 EDT 2006
charles.hebert at gmail.com 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 ?
>
> Thanks,
>
> CH.
>
One of I'm sure many ways:
import sys
def closest(value, list):
m=None
mdistance=sys.maxint
for entry in list:
distance=abs(value-entry)
if distance < mdistance:
m=entry
mdistance=distance
return m
if __name__ == "__main__":
foo = [-5,-1,2,3]
print closest(0, foo)
Note: If you know that the list is ordered you can break out of the
loop you can optimize the loop by breaking out when you start getting
further away from value or you might be able to use the bisect module
to find it faster. If the lists are small it probably isn't worth
the extra effort. If they are large and sorted look at bisect.
Question: what if two values are equidistant?
-Larry bATES
More information about the Python-list
mailing list