You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 18:36:06