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

Python中如何统计列表连续0块的数量及对应起止位置

Python 连续0块统计实现

完整实现代码

def count_zero_blocks(arr):
    zero_blocks = []
    current_start = None
    # 遍历数组的索引与对应值
    for idx, num in enumerate(arr):
        if num == 0:
            # 首次进入0块,记录起始位置
            if current_start is None:
                current_start = idx
        else:
            # 离开0块,保存起止信息并重置标记
            if current_start is not None:
                zero_blocks.append((current_start, idx - 1))
                current_start = None
    # 处理数组末尾为0的边界场景,避免漏统计
    if current_start is not None:
        zero_blocks.append((current_start, len(arr) - 1))
    return zero_blocks

# 测试调用
a = [1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1]
result = count_zero_blocks(a)
# 按要求格式输出
for count, (start, end) in enumerate(result, start=1):
    print(f"Position start {start}, Position end {end}, Count {count}")

输出结果

和需求示例的前3项完全匹配,剩余块按实际数组内容正常统计:

Position start 5, Position end 8, Count 1
Position start 12, Position end 12, Count 2
Position start 14, Position end 14, Count 3
Position start 16, Position end 16, Count 4
Position start 28, Position end 33, Count 5
Position start 36, Position end 36, Count 6
Position start 38, Position end 38, Count 7
Position start 40, Position end 40, Count 8

核心逻辑说明

  • 用current_start变量标记当前0块的起始位置,未进入0块时设为None
  • 遍历数组时首次遇到0,记录当前索引为块起始位置
  • 遍历到非0值时如果处于0块中,说明当前块结束,结束位置为当前索引减1,将起止位置存入结果列表后重置标记
  • 遍历结束后额外判断标记位,避免数组末尾是0的场景出现漏统计

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 18:18:03