Python嵌套列表处理:为对应子列表添加分组标识前缀
嵌套列表分组处理解决方案
需求回顾
- 跳过所有仅含分隔符(如
['----------'])的子列表 - 提取每个分组的标题项(首元素为字符串的子列表,比如
['one', 1]) - 将标题项添加到对应分组后续每个子列表的开头,生成最终列表
代码实现
big_list = [['----------'], ['one', 1], [2,3,'hi','hello'], [2,3,'hi'], ['----------'], ['two', 2], [2,3,'hi'], [2,3,'hi','bye','bye']] result = [] current_title = None for sublist in big_list: # 跳过分隔符子列表 if len(sublist) == 1 and sublist[0].startswith('-'): continue # 识别分组标题(首元素为字符串的子列表) if isinstance(sublist[0], str): current_title = sublist else: # 将标题拼接到当前子列表头部,存入结果 if current_title is not None: result.append([current_title] + sublist) # 输出结果 print(result)
代码说明
- 初始化变量:
result用来存储最终处理后的列表,current_title临时保存当前分组的标题 - 遍历处理每个子列表:
- 遇到分隔符子列表直接跳过
- 遇到首元素是字符串的子列表,更新
current_title为该子列表 - 遇到普通内容子列表,把
current_title作为第一个元素拼接到子列表前,添加到result中
运行结果
执行代码后会得到目标结果:
[[['one', 1], 2, 3, 'hi', 'hello'], [['one', 1], 2, 3, 'hi'], [['two', 2], 2, 3, 'hi'], [['two', 2], 2, 3, 'hi', 'bye', 'bye']]
内容的提问来源于stack exchange,提问作者Ella
相关产品推荐
相关产品推荐

