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

如何基于分隔符'...'将字符串列表转为嵌套字符串列表?

按分隔符拆分列表为嵌套列表

我有如下字符串列表:

example = ['1','4','6','7','9','...','11','14','18','...','21']

需要以'...'作为分隔符,将其转换为嵌套列表,期望输出如下:

output = [['1','4','6','7','9'],['11','14','18'],['21']]

我自己实现的代码如下,但感觉比较繁琐:

output = []
temp_list = []
for sign in example:
    if sign == '...':
        output.append(temp_list)
        temp_list = []
    else:
        temp_list.append(sign)
output.append(temp_list)

更简洁的实现方式

方法一:使用itertools.groupby

借助itertools.groupby按元素是否为分隔符分组,过滤掉分隔符对应的分组后即可得到结果:

from itertools import groupby

example = ['1','4','6','7','9','...','11','14','18','...','21']
output = [list(group) for is_valid, group in groupby(example, key=lambda x: x != '...') if is_valid]

方法二:自定义生成器函数

如果不想引入额外库,可以用生成器封装拆分逻辑,代码可读性更强:

def split_by_sep(lst, sep):
    current_group = []
    for item in lst:
        if item == sep:
            if current_group:
                yield current_group
                current_group = []
        else:
            current_group.append(item)
    # 处理最后一组未被分隔符收尾的元素
    if current_group:
        yield current_group

example = ['1','4','6','7','9','...','11','14','18','...','21']
output = list(split_by_sep(example, '...'))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 07:12:42