UnlimitedQuestions -3 years ago 104

Python Question

For example I have array x

`x = [10, 100, 1000, 10000]`

If I have the number 600, then how can I get the values 100 as the lower value and 1000 as the upper value.

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

Assuming the input as sorted, we can use `np.searchsorted`

to get the index where `600`

could be placed in that sorted order and then simply use the index and one-off shifted index to get the lower, upper limits upon indexing, like so -

```
idx = np.searchsorted(x,600)
out = x[idx-1], x[idx]
```

Sample run -

```
In [41]: x = [10, 100, 1000, 10000]
In [42]: idx = np.searchsorted(x,600)
In [44]: x[idx-1], x[idx]
Out[44]: (100, 1000)
```

We can also use `bisect`

module, which I believe could be a bit faster -

```
import bisect
idx = bisect.bisect_left(x,600)
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**

Latest added