简体   繁体   中英

Find index of the first value that is below/above a threshold

I have a list with a series of random floats that go from negative to positive, like:

values = [0.001, 0.05, 0.09, 0.1, 0.4, 0.8, 0.9, 0.95, 0.99]

I wish to filter out the indices that first meet the greater than/less than values that I wish. For example, if I want the first closest value less than 0.1 I would get an index of 2 and if I want the first highest value greater than 0.9 I'd get 7 .

I have a find_nearest method that I am using but since this dataset is randomized, this is not ideal.

EDIT: Figured out a solution.

low = next(x[0] for x in enumerate(list(reversed(values))) if x[1] < 0.1)
high = next(x[0] for x in enumerate(values) if x[1] > 0.9)

if the values list gets long you may want the bisect module from the standard lib

bisect_left , bisect_right may serve as the > , < tests

import bisect
values = [0.001, 0.05, 0.09, 0.1, 0.4, 0.8, 0.9, 0.95, 0.99]
bisect.bisect_left(values, .1)
Out[226]: 3

bisect.bisect_right(values, .1)
Out[227]: 4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM