![](/img/trans.png)
[英]Find the first index for which an array goes below a certain threshold (and stay below for some time)
[英]Find index of the first value that is below/above a threshold
我有一個列表,其中包含一系列從負到正的隨機浮點數,例如:
values = [0.001, 0.05, 0.09, 0.1, 0.4, 0.8, 0.9, 0.95, 0.99]
我希望篩選出首先滿足大於/小於期望值的索引。 例如,如果我想使第一個最接近的值小於0.1,那么我將得到2
的索引,如果我想使第一個最接近的值大於0.9,我將得到7
。
我有一個find_nearest
方法,但是由於此數據集是隨機的,因此不理想。
編輯:找出解決方案。
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)
如果值列表過長,則可能需要標准庫中的bisect模塊
bisect_left
, bisect_right
可以用作>
, <
測試
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.