如何在Python嵌套列表的子列表每个元素后插入0
Python嵌套列表元素插入实现方案
核心代码
你可以直接用下面的代码完成需求:
# 原始嵌套列表 sep = [['IN', 'the', 'midway', 'of', 'this', 'our', 'mortal', 'life'], ['I', 'found', 'me', 'in', 'a', 'gloomy', 'wood', 'astray'], ['Gone', 'from', 'the', 'path', 'direct', 'and', 'e','en', 'to', 'tell'], ['It', 'were', 'no', 'easy', 'task', 'how', 'savage', 'wild'], ['That','forest', 'how', 'robust', 'rough', 'its', 'growth'], ['Which', 'to', 'remember', 'only', 'my', 'dismay'], ['Renews', 'in', 'bitterness', 'not', 'far', 'from', 'death']] # 实现方式1:生成新列表(不修改原始数据,推荐) processed_sep = [] for sub_list in sep: new_sub = [] for word in sub_list: new_sub.append(word) new_sub.append('0') processed_sep.append(new_sub) # 实现方式2:一行列表推导式(简洁写法,效果和上面完全一致) processed_sep = [[i for word in sub for i in (word, '0')] for sub in sep] # 实现方式3:原地修改原始列表 for sub in sep: # 从索引1开始,每次间隔2位插入0 for idx in range(1, len(sub)*2, 2): sub.insert(idx, '0')
逻辑说明
- 生成新列表的方式不会改动你原来的
sep数据,适合需要保留原始数据的场景 - 原地修改的方式直接改动原列表,不需要额外的存储空间,适合不需要保留原始数据的场景
运行以上任意一种实现后的结果和你给出的预期输出完全一致。
内容的提问来源于stack exchange,提问作者Dino
相关产品推荐
相关产品推荐

