文章目录
经常会遇到一种场景,那就是有一个一维向量,我们要找到其中所有大于设定阈值的片段。就好比电路中有高代电平,我们要找连续的高电平段或低电平:
如上图,我们只要标红的高电平,对应代码:
import numpy as np
def extract_segments(v, a):
"""v是向量,a是我们设定的阈值
Args:
v (_type_): _description_
a (_type_): _description_
Returns:
_type_: _description_
"""
segments = []
current_segment = []
for i in range(len(v)):
if v[i] > a:
current_segment.append(v[i])
else:
if len(current_segment) > 0:
segments.append(current_segment)
current_segment = []
if len(current_segment) > 0:
segments.append(current_segment)
return segments
测试结果: