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

如何从数字列表中识别至少五个连续元素并拆分到新列表

问题分析与修改方案

原代码问题说明

  • 追加到IDs的是循环下标i而非flags中对应的实际索引值,导致内容完全不符
  • 连续长度统计逻辑没有和结果筛选挂钩,也没有处理连续序列中断后的重置、结果校验逻辑

修正后实现代码

flags = [0, 1, 3, 4, 5, 6, 7, 14, 15, 16, 17, 19, 20, 26]
result = []
current_sequence = []

for num in flags:
    if not current_sequence or num == current_sequence[-1] + 1:
        current_sequence.append(num)
    else:
        # 连续序列中断,校验长度是否符合要求
        if len(current_sequence) >= 5:
            result.append(current_sequence)
        current_sequence = [num]
# 遍历结束后校验最后一段序列
if len(current_sequence) >=5:
    result.append(current_sequence)

print(result)  # 输出:[[3, 4, 5, 6, 7]]
# 如果你只需要第一个符合要求的序列,直接取result[0]即可

补充说明

  • 如果存在多段符合长度要求的连续序列,上述代码会全部存入result列表
  • 若仅需提取第一个符合要求的序列,匹配到后可以直接加break终止循环提升效率

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 20:45:05