如何用Python获取0-1序列中各连续0段的起始索引?
获取二进制序列中连续0段的起始索引(Python实现)
Python没有直接满足该需求的内置函数,但可以通过简单的遍历逻辑轻松实现。以下是具体的实现思路和代码:
核心逻辑
遍历序列时,跟踪当前是否处于连续0的片段中:
- 当遇到0且之前未处于0片段时,记录当前索引作为该段0的起始位置
- 当遇到1时,标记为退出0片段
- 遍历结束后,若没有找到任何0片段,返回
NULL;否则返回所有起始索引
实现代码
def get_zero_start_indices(seq): start_indices = [] in_zero_segment = False for idx, num in enumerate(seq): if num == 0: if not in_zero_segment: start_indices.append(idx) in_zero_segment = True else: in_zero_segment = False return start_indices if start_indices else "NULL"
如果需要返回逗号分隔的字符串格式(匹配示例中的输出样式),可以在上述基础上封装一层:
def get_zero_start_indices_str(seq): indices = get_zero_start_indices(seq) return "NULL" if indices == "NULL" else ", ".join(map(str, indices))
测试案例
示例1
seq1 = [0,0,0,0,1,1,1,0,1,0,1,0,1,1,1] print(get_zero_start_indices_str(seq1)) # 输出: 0, 7, 9, 11
示例2
seq2 = [1,1,1,1,0,0,0,1,0] print(get_zero_start_indices_str(seq2)) # 输出: 4, 8
示例3
seq3 = [0,0,0,0,0,0] print(get_zero_start_indices_str(seq3)) # 输出: 0
示例4
seq4 = [1,1,1,1] print(get_zero_start_indices_str(seq4)) # 输出: NULL
内容的提问来源于stack exchange,提问作者Brian Smith
相关产品推荐
相关产品推荐

