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

Python如何遍历列表分组文件并调用merge_txt函数完成合并?

实现代码

首先修正你提供的data列表的语法错误(0004第三个源文件条目末尾缺逗号),完整实现如下:

from collections import defaultdict

# 补全语法错误后的源数据列表
data = [
    {'fn': '1_0001_01.txt', 'file': '0001.txt'},
    {'fn': '1_0001_02.txt', 'file': '0001.txt'},
    {'fn': '1_0001_03.txt', 'file': '0001.txt'},
    {'fn': '1_0002_01.txt', 'file': '0002.txt'},
    {'fn': '1_0002_02.txt', 'file': '0002.txt'},
    {'fn': '1_0003_01.txt', 'file': '0003.txt'},
    {'fn': '1_0003_02.txt', 'file': '0003.txt'},
    {'fn': '1_0003_03.txt', 'file': '0003.txt'},
    {'fn': '1_0004_01.txt', 'file': '0004.txt'},
    {'fn': '1_0004_02.txt', 'file': '0004.txt'},
    {'fn': '1_0004_03.txt', 'file': '0004.txt'},
    {'fn': '1_0005_01.txt', 'file': '0005.txt'},
    {'fn': '1_0005_02.txt', 'file': '0005.txt'},
    {'fn': '1_0005_03.txt', 'file': '0005.txt'}
]

# 按目标文件名字段分组
grouped_files = defaultdict(list)
for item in data:
    grouped_files[item["file"]].append(item["fn"])

# 遍历分组结果调用合并函数
for target_filename, source_file_list in grouped_files.items():
    merge_txt(source_file_list, target_filename)
不用额外导入模块的实现

如果不想导入collections标准库,也可以用普通字典完成分组:

grouped_files = {}
for item in data:
    target = item["file"]
    source = item["fn"]
    if target not in grouped_files:
        grouped_files[target] = []
    grouped_files[target].append(source)

# 调用合并函数的逻辑和上文一致
for target_filename, source_file_list in grouped_files.items():
    merge_txt(source_file_list, target_filename)
逻辑说明
  • 遍历原始数据列表,以每个元素的file字段作为分组键,把对应的fn值追加到该键对应的列表中,完成按目标文件的分组
  • 遍历分组后的字典,每一组的键就是要生成的目标文件名,值就是对应需要合并的源文件列表,直接传入你已有的merge_txt函数即可执行合并

内容的提问来源于stack exchange,提问作者Tinke

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 18:18:02