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

如何在Python列表中统计连续相同数字并执行指定计算

实现连续1组的统计替换与非1元素转换

问题描述

给定原始列表:

original_list = [6, 1, 1, 1, 5, 1, 7, 1, 7, 1, 7, 7, 7, 1, 7, 1, 1, 3, 1, 1, 1, 1]

需求如下:

  1. 统计每组连续1的个数,将每组替换为「个数+1」的结果(每组仅保留一个值),得到中间列表;
  2. 将中间列表中所有非原1组替换来的数值,全部替换为1,保留原1组替换后的结果,得到最终列表。

实现代码

original_list = [6, 1, 1, 1, 5, 1, 7, 1, 7, 1, 7, 7, 7, 1, 7, 1, 1, 3, 1, 1, 1, 1]
intermediate = []
# 记录中间列表中需要保留的位置(即原连续1组替换后的位置)
keep_indices = []
i = 0
total_length = len(original_list)

# 第一步:生成中间列表,统计连续1组并替换
while i < total_length:
    if original_list[i] == 1:
        # 统计当前连续1的数量
        consecutive_count = 0
        while i < total_length and original_list[i] == 1:
            consecutive_count += 1
            i += 1
        # 计算替换值并加入中间列表
        replace_value = consecutive_count + 1
        intermediate.append(replace_value)
        keep_indices.append(len(intermediate) - 1)
    else:
        # 非1元素直接加入中间列表
        intermediate.append(original_list[i])
        i += 1

# 第二步:生成最终列表,替换非保留位置的元素为1
final_list = []
for idx, num in enumerate(intermediate):
    if idx in keep_indices:
        final_list.append(num)
    else:
        final_list.append(1)

# 输出结果
print("中间列表:", intermediate)
print("最终列表:", final_list)

代码说明

  1. 生成中间列表:通过遍历原始列表,遇到连续的1时统计其长度,计算「长度+1」的值加入中间列表,同时记录该值在中间列表中的索引;非1元素直接加入中间列表。
  2. 生成最终列表:遍历中间列表,仅保留记录索引位置的数值,其余所有元素替换为1,得到需求的最终结果。

输出结果

中间列表: [6, 4, 5, 2, 7, 2, 7, 2, 7, 7, 7, 2, 7, 3, 5]
最终列表: [1, 4, 1, 2, 1, 2, 1, 2, 1, 1, 1, 2, 1, 1, 5]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 10:25:13