Determining Where A Value Lies From A List Of Intervals (synthetic Solution)
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
andhi
may be used to specify a subset of the list which should be considered; by default the entire list is used. Ifx
is already present ina
, the insertion point will be before (to the left of) any existing entries. The return value is suitable for use as the first parameter tolist.insert()
assuming that a is already sorted.The returned insertion point
i
partitions the arraya
into two halves so thatall(val < x for val in a[lo:i])
for the left side andall(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)"