Python列表处理:如何编写循环每N个元素后合并相邻两项
完整实现代码
file = 'data.txt' corrected = [] one = [] two = [] three = [] full = [one, two, three] with open(file, 'r') as f: contents = f.read() # 避免用list做变量名,和Python内置关键字冲突 raw_list = contents.split() # 第一步:过滤所有带冒号、右括号的键元素,保留纯值列表 filtered = [item for item in raw_list if ':' not in item and ')' not in item] # 第二步:按规则批量合并元素,适配任意数量同格式数据 i = 0 while i < len(filtered): # 每组第一个值直接加入 corrected.append(filtered[i]) # 合并每组相邻的两个文本值 corrected.append(f"{filtered[i+1]} {filtered[i+2]}") # 每组第三个值直接加入 corrected.append(filtered[i+3]) i += 4 # 第三步:按位置拆分到三个输出列表 for item in corrected[::3]: one.append(item) for item in corrected[1::3]: two.append(item) for item in corrected[2::3]: three.append(item) # 输出结果 index = 1 for item in full: print(f"{index}:{item}") index += 1
运行后输出完全符合预期:
1:['8473', '583'] 2:['second text', 'sec text'] 3:['23-54-65-87', '5343-436654-98989']
内容的提问来源于stack exchange,提问作者senluowanxiangxiaoyaozizai
相关产品推荐
相关产品推荐

