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

如何查找列表中值为4的连续块的起止索引?

实现方案

问题说明

给定列表:

i_have = [1,1,1,4,4,4,4,4,4,4,1,1,1,1,4,4,4,4,3,3,4,3]

需要找出所有值为4的连续元素块的起始和结束索引;若为单个4,起止索引保持一致,期望结果:

i_need = [(3, 9), (14, 17), (20, 20)]

Python 实现代码

通过遍历列表并跟踪连续4块的起始位置即可实现:

i_have = [1,1,1,4,4,4,4,4,4,4,1,1,1,1,4,4,4,4,3,3,4,3]
i_need = []
start_idx = None

for idx, num in enumerate(i_have):
    if num == 4:
        if start_idx is None:
            start_idx = idx
    else:
        if start_idx is not None:
            i_need.append((start_idx, idx - 1))
            start_idx = None
# 处理列表末尾可能遗留的连续4块
if start_idx is not None:
    i_need.append((start_idx, len(i_have) - 1))

print(i_need)  # 输出: [(3, 9), (14, 17), (20, 20)]

逻辑说明

  • 用start_idx记录连续4块的起始索引,初始值为None表示未进入4的连续块
  • 遍历列表时,遇到4且start_idx为None,则记录当前索引为起始位置
  • 遇到非4且start_idx不为None,则将当前连续块的起止索引加入结果列表,并重置start_idx
  • 遍历结束后,检查是否存在未处理的末尾连续4块,若有则补充到结果中

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 03:45:36