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

Python列表去重并添加特殊字符求助:已完成去重但无法添加字符

解决连续重复元素替换为特殊字符+元素的Python实现

需求:读取列表中的每个元素,将连续重复的元素替换为指定特殊字符(如示例中的BB)加上该元素一次;非连续重复的元素保留原样。例如输入[15, 16, 17, 17, 17, 18, 19],输出为15 16 BB 17 18 19。

现有代码的问题

你的代码存在几个核心逻辑错误:

  • 内层循环无意义地修改临时列表reser,导致输出混乱的中间状态
  • 未区分「连续重复」和「全局重复」(比如测试列表末尾的25是单独出现的,不应被当成重复处理)
  • 没有构建最终的结果集合,不符合输出需求

正确实现代码

def process_consecutive_duplicates(input_list, special_tag="BB"):
    if not input_list:
        return ""
    
    processed = []
    index = 0
    total_length = len(input_list)
    
    while index < total_length:
        current_item = input_list[index]
        # 统计当前元素连续出现的次数
        consecutive_count = 1
        while index + consecutive_count < total_length and input_list[index + consecutive_count] == current_item:
            consecutive_count += 1
        
        # 根据连续次数添加对应内容
        if consecutive_count > 1:
            processed.append(special_tag)
            processed.append(str(current_item))
        else:
            processed.append(str(current_item))
        
        # 跳过已处理的连续元素
        index += consecutive_count
    
    return " ".join(processed)

# 测试示例
test_list1 = [15, 16, 17, 17, 17, 18, 19]
print(process_consecutive_duplicates(test_list1))  # 输出: 15 16 BB 17 18 19

test_list2 = [22, 23, 24, 24, 24, 24, 24, 24, 24, 25, 27, 27, 27, 27, 27, 27, 25]
print(process_consecutive_duplicates(test_list2))  # 输出: 22 23 BB 24 25 BB 27 25

代码逻辑说明

  1. 先处理空列表的边界情况,避免报错
  2. 用外层while循环遍历列表,每次定位当前元素
  3. 内层while循环统计当前元素连续出现的次数
  4. 根据连续次数判断:次数大于1时,先添加特殊标记再添加元素;次数为1时直接添加元素
  5. 最后用join方法将结果列表拼接为空格分隔的字符串,符合输出格式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 02:36:14