where or filter on list

Neil Cerutti horpner at yahoo.com
Wed Aug 30 09:43:07 EDT 2006


On 2006-08-30, charles.hebert at gmail.com <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 ?

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



More information about the Python-list mailing list