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

Python如何实现列表中多次重复连续元素的自动合并算法

连续重复序列合并实现方案

现有代码核心问题

  • 遍历步长固定为1,合并i和i+1位置的元素后,i+1位置会被二次遍历,导致字符重复输出
  • 仅单次处理长度为2的元素组合,没有迭代合并更长的重复序列,无法得到完整的合并结果

实现思路

采用迭代合并的方案,从最短的二元组开始合并,每次合并完更新当前列表后重复检测,直到没有可合并的组合为止:

  1. 初始将输入字符串转为单字符列表作为当前处理列表
  2. 统计当前列表中所有相邻二元组的出现频率
  3. 若不存在出现次数≥2的二元组,结束循环返回结果
  4. 若存在可合并的二元组,从左到右遍历当前列表:
    • 遇到出现次数≥2的二元组,合并为单个元素加入结果列表,索引步进2
    • 否则将当前单个元素加入结果列表,索引步进1
  5. 将结果列表作为新的当前处理列表,重复步骤2的检测

可运行代码

def merge_repeated_sequence(input_str):
    # 初始转为单字符列表
    current_list = list(input_str)
    
    while True:
        # 统计当前列表所有相邻二元组的出现次数
        pair_count = {}
        for i in range(len(current_list) - 1):
            pair = (current_list[i], current_list[i+1])
            pair_count[pair] = pair_count.get(pair, 0) + 1
        
        # 没有可以合并的二元组,结束循环
        if all(count < 2 for count in pair_count.values()):
            break
        
        # 遍历合并
        new_list = []
        idx = 0
        while idx < len(current_list):
            # 还有下一个元素,且当前二元组可合并
            if idx < len(current_list) - 1 and pair_count.get((current_list[idx], current_list[idx+1]), 0) >= 2:
                new_list.append(current_list[idx] + current_list[idx+1])
                idx += 2
            else:
                new_list.append(current_list[idx])
                idx += 1
        current_list = new_list
    
    return current_list

测试效果

测试用例1:hello yellow

print(merge_repeated_sequence("hello yellow"))
# 输出:['h', 'ello', ' ', 'y', 'ello', 'w']

测试用例2:hello hello world

print(merge_repeated_sequence("hello hello world"))
# 输出:['hello ', 'hello ', 'w', 'o', 'r', 'l', 'd']

测试用例3:hello there

print(merge_repeated_sequence("hello there"))
# 输出:['he', 'l', 'l', 'o', ' ', 't', 'he', 'r', 'e']

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 09:42:00