Python遍历列表:提取指定元素区间内容并格式化
问题:提取列表指定区间内容并格式化
原始列表
list1 = [ 'some', 'thing', 'is', 'here', 'dont', 'care', 'them', 'The process completed', 'process id: p1', 'process id: p2', 'Regards', 'some', 'thing', 'is', 'here', 'dont', 'care', 'them', 'The process completed', 'process id: p12', 'Regards', ]
预期输出
list3 = [ 'The process completed:\nprocess id: p1, process id: p2', 'The process completed:\nprocess id: p12' ]
需求说明
提取从The process completed开始到Regards结束的内容(不包含Regards本身),并按上述格式拼接为字符串存入新列表。
尝试的错误代码
new_list = [] new_str = '' for l in list1: if l == 'The process completed': new_str += l new_str += l if l == 'Regards': new_list.append(new_str) new_str = '' pass
正确实现方案
通过标记目标区间的方式处理:
list1 = [ 'some', 'thing', 'is', 'here', 'dont', 'care', 'them', 'The process completed', 'process id: p1', 'process id: p2', 'Regards', 'some', 'thing', 'is', 'here', 'dont', 'care', 'them', 'The process completed', 'process id: p12', 'Regards', ] new_list = [] current_group = [] in_target = False for item in list1: if item == 'The process completed': in_target = True current_group.append(item) elif item == 'Regards': if in_target: # 按预期格式拼接内容 header = f"{current_group[0]}:" details = ', '.join(current_group[1:]) new_list.append(f"{header}\n{details}") # 重置临时分组和标记 current_group = [] in_target = False elif in_target: current_group.append(item) # 验证结果 print(new_list)
代码逻辑说明
- 用
in_target变量标记是否进入需要提取的区间 - 遇到
The process completed时开启标记,并将该元素加入临时分组 - 遇到
Regards时,若处于目标区间,就把临时分组的内容按格式拼接后加入结果列表,随后重置状态 - 处于目标区间时,将
Regards之外的后续元素都加入临时分组
内容的提问来源于stack exchange,提问作者Saeed
相关产品推荐
相关产品推荐

