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

如何将列表中以指定字符串结尾的连续元素合并为子列表

列表转换实现方案

核心逻辑为单次遍历原列表,维护临时缓存存储待分组元素,遇到join标记时将当前缓存打包为子列表存入结果并清空缓存,遍历结束后将剩余未分组的元素直接追加到结果末尾。

代码实现

def convert_list(input_list):
    result = []
    temp_buffer = []
    for elem in input_list:
        temp_buffer.append(elem)
        if elem == "join":
            result.append(temp_buffer)
            temp_buffer = []
    # 追加剩余未分组元素
    result.extend(temp_buffer)
    return result

# 测试用例
i = ["file1", "file2", "join", "file3", "file4", "join", "file5", "file6"]
o = convert_list(i)
print(o)
# 输出:[['file1', 'file2', 'join'], ['file3', 'file4', 'join'], 'file5', 'file6']

该方案仅需一次遍历即可完成转换,时间复杂度为O(n),无需复杂的pop、index操作即可适配需求场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 07:27:01