You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何从点列表中提取阈值以上连续点及对应索引

连续高于阈值点段提取实现

需求说明

你已生成由0、1组成的阈值判断标记列表:points_above_threshold,其中1代表对应索引位置的数据点高于阈值,0代表未达阈值。需要提取列表中所有连续为1的片段,每个片段按[连续点数量, (起始索引, 结束索引)]的格式返回,同时支持按需获取对应段的原始点取值。

实现代码

def get_continuous_above_segments(points_mark):
    result = []
    list_length = len(points_mark)
    current_idx = 0
    while current_idx < list_length:
        # 定位连续高于阈值段的起点
        if points_mark[current_idx] == 1:
            seg_start = current_idx
            # 遍历到连续段结束位置
            while current_idx < list_length and points_mark[current_idx] == 1:
                current_idx += 1
            seg_end = current_idx - 1
            result.append([current_idx - seg_start, (seg_start, seg_end)])
        current_idx += 1
    return result

示例验证

使用给出的测试用例运行:

points_above_threshold = [1,1,1,0,0,0,1,1]
print(get_continuous_above_segments(points_above_threshold))

运行输出完全匹配预期:

[[3, (0, 2)], [2, (6, 7)]]

扩展说明

如果需要获取每个连续段对应的原始数据取值,只需要传入原始数据列表,在记录段信息时同步切片即可:

def get_continuous_segments_with_value(points_mark, raw_data):
    result = []
    list_length = len(points_mark)
    current_idx = 0
    while current_idx < list_length:
        if points_mark[current_idx] == 1:
            seg_start = current_idx
            while current_idx < list_length and points_mark[current_idx] == 1:
                current_idx += 1
            seg_end = current_idx - 1
            # 切片取出对应段的原始值
            seg_values = raw_data[seg_start:seg_end+1]
            result.append([current_idx - seg_start, (seg_start, seg_end), seg_values])
        current_idx += 1
    return result

内容的提问来源于stack exchange,提问作者Zaeem Sheikh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 09:24:14