如何查找列表中值为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
相关产品推荐
相关产品推荐

