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

如何用Python统计列表中相邻两个1之间的0的数量?

统计列表中相邻两个1之间的0的数量

针对你的需求,这里提供两种Python实现方式,都能得到预期结果:

方法一:基于索引计算

先收集所有1在列表中的索引,再通过相邻索引的差值计算中间0的数量,最后过滤掉连续1的情况(差值为1,中间0数量为0):

l = [0,1,0,0,0,0,1,1,1,0,0,1,0,1,1,0]
# 提取所有值为1的元素的索引
one_indices = [idx for idx, val in enumerate(l) if val == 1]
# 计算相邻两个1之间的0的数量,仅保留大于0的结果
result = [one_indices[i+1] - one_indices[i] - 1 for i in range(len(one_indices)-1) 
          if one_indices[i+1] - one_indices[i] - 1 > 0]
print(result)  # 输出: [4,2,1]

方法二:遍历计数法

通过遍历列表,实时统计两个1之间的0的数量,遇到1时判断是否需要记录当前计数:

l = [0,1,0,0,0,0,1,1,1,0,0,1,0,1,1,0]
result = []
zero_count = 0
has_seen_first_one = False

for num in l:
    if num == 1:
        if has_seen_first_one:
            # 已经遇到过第一个1,现在遇到新的1,检查之前的计数
            if zero_count > 0:
                result.append(zero_count)
                zero_count = 0
        else:
            # 标记第一次遇到1
            has_seen_first_one = True
    else:
        # 只在遇到第一个1之后统计0的数量
        if has_seen_first_one:
            zero_count += 1

print(result)  # 输出: [4,2,1]

说明

  • 两种方法都会忽略列表开头未遇到1前的0,以及列表结尾最后一个1之后的0
  • 连续出现的1之间没有0,这类情况会被自动过滤,不会加入结果列表

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 00:05:24