[SciPy-user] finding values in a list?

Alan McIntyre alan.mcintyre@gmail....
Sat Jul 11 16:21:02 CDT 2009


2009/7/11 Carlos "Guâno" Grohmann <carlos.grohmann@gmail.com>:
> Sorry if this is too simple or even OT, but say I have a list like
>
> [1,2,3,4,5,6,7,8,9]
>
> and I want to get the values just below and above a given value.
>
> So, if I enter 6.2, I get 6 and 7.
>
> but how?

There's probably more efficient ways to do it, but this works:

def get_nearest(a, v):
     '''Get the values in 'a' that bracket 'v'.  Assumes a is a list
already sorted in ascending order.'''
     A = np.array(a)
     return A[A < v][-1], A[A > v][0]

get_nearest([1,2,3,4,5,6,7,8,9], 6.2)
[6, 7]


More information about the SciPy-user mailing list