Skip to content Skip to sidebar Skip to footer

Determining Where A Value Lies From A List Of Intervals (synthetic Solution)

I have a list l of increasing values, for example import numpy as np l=np.linspace(0.,1.,10) For a number a=0.225, I want to find the index i such that l[i]

Solution 1:

As mentioned in the comments, for l being sorted, we can use np.searchsorted -

np.searchsorted(l,a,'right')-1

Or with np.digitize -

np.digitize(a,l,right=True)-1

Solution 2:

For a pure python solution, there is the bisect module:

>>> from bisect import bisect_left
>>> a = list(range(1, 10))
>>> bisect_left(a, 3.5)
3

or with numpy:

>>> from bisect import bisect_left
>>> import numpy as np
>>> l = np.linspace(0, 1, 10)
>>> bisect_left(l, 0.225)
3

bisect.bisect_left(a, x, lo=0, hi=len(a))

Locate the insertion point for x in a to maintain sorted order. The parameters lo and hi may be used to specify a subset of the list which should be considered; by default the entire list is used. If x is already present in a, the insertion point will be before (to the left of) any existing entries. The return value is suitable for use as the first parameter to list.insert() assuming that a is already sorted.

The returned insertion point i partitions the array a into two halves so that all(val < x for val in a[lo:i]) for the left side and all(val >= x for val in a[i:hi]) for the right side.

Post a Comment for "Determining Where A Value Lies From A List Of Intervals (synthetic Solution)"