如何基于分隔符'...'将字符串列表转为嵌套字符串列表?
按分隔符拆分列表为嵌套列表
我有如下字符串列表:
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
相关产品推荐
相关产品推荐

