You need to enable JavaScript to run this app. 如何获取main_list中连续True不少于3次的片段起始索引 无需numpy/groupby
优惠活动
大模型
产品
解决方案
定价
更多

如何获取main_list中连续True不少于3次的片段起始索引 无需numpy/groupby

代码修改方案

核心思路

你原有代码的问题是仅记录了所有连续True片段的起始索引,没有判断片段长度是否符合要求。修改逻辑为:每次找到连续True的起始位置后,先遍历完当前整段连续True,计算片段长度,仅当长度≥min_segment时,才将起始索引加入结果列表。

可直接运行的代码

min_segment = 3
main_list = [True, True, False, False, True, True, True, True, True, False, False, True, True,True]
i = 0
true_index = []
list_length = len(main_list)

while i < list_length:
    if main_list[i]:
        # 记录当前连续True片段的起始位置
        current_start = i
        # 遍历到当前连续True片段结束
        while i < list_length and main_list[i]:
            i += 1
        # 判断片段长度是否符合要求
        if i - current_start >= min_segment:
            true_index.append(current_start)
    else:
        i += 1

print(true_index)

运行后输出结果为:

[4, 11]

代码说明

  • 不需要引入任何第三方库,仅用基础循环实现,逻辑清晰易读
  • 一次遍历即可完成统计,时间复杂度为O(n),效率较高
  • 可以通过修改min_segment的值灵活调整连续True的最小长度要求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 01:09:00