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

如何在Python中从布尔数组提取至少6个连续True值并保留原始索引

实现方案

方案1:纯Python原生实现(无需第三方依赖)

思路是遍历数组记录连续True的区间,筛选长度≥6的区间后生成结果数组:

def filter_continuous_true(arr, min_length=6):
    n = len(arr)
    result = [False] * n
    start = None
    for i, val in enumerate(arr):
        if val:
            if start is None:
                start = i
        else:
            if start is not None:
                # 计算连续True的长度
                length = i - start
                if length >= min_length:
                    # 对应区间设为True
                    for j in range(start, i):
                        result[j] = True
                start = None
    # 处理数组末尾的连续True段
    if start is not None:
        length = n - start
        if length >= min_length:
            for j in range(start, n):
                result[j] = True
    return result

# 测试示例
input_arr = [True, True, True, True, True, True, False, False, False, False, False, True , True , False, False, False]
output_arr = filter_continuous_true(input_arr)
print(output_arr)
# 输出:[True, True, True, True, True, True, False, False, False, False, False, False, False, False, False, False]

方案2:NumPy实现(处理长数组效率更高)

Jupyter Lab环境通常默认预装NumPy,可使用更简洁的向量化操作实现:

import numpy as np

def filter_continuous_true_np(arr, min_length=6):
    arr_np = np.asarray(arr, dtype=bool)
    n = len(arr_np)
    result = np.zeros(n, dtype=bool)
    # 找连续True段的起止位置
    diff = np.diff(np.concatenate(([False], arr_np, [False])))
    starts = np.where(diff == 1)[0]
    ends = np.where(diff == -1)[0]
    # 筛选符合长度要求的段
    mask = (ends - starts) >= min_length
    for s, e in zip(starts[mask], ends[mask]):
        result[s:e] = True
    return result.tolist()

# 测试示例
input_arr = [True, True, True, True, True, True, False, False, False, False, False, True , True , False, False, False]
output_arr = filter_continuous_true_np(input_arr)
print(output_arr)
# 输出:[True, True, True, True, True, True, False, False, False, False, False, False, False, False, False, False]

补充说明

  • 两种方案都会保留原始索引位置,不符合长度要求的连续True段会统一设为False,和给出的示例输出完全一致
  • 针对长度为1320的数组,两种方案的执行效率都完全满足需求,无需担心性能问题

内容的提问来源于stack exchange,提问作者Johan Edholm

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 15:15:06