You need to enable JavaScript to run this app. Python拆分固定格式文件名并按ID对对应索引值求和
优惠活动
大模型
产品
解决方案
定价
更多

Python拆分固定格式文件名并按ID对对应索引值求和

实现方案

你可以用字典存储每个ID对应的索引总和,遍历过程中直接累加即可,以下是修改后可直接运行的代码:

from collections import defaultdict

# 这里用示例数据做测试,实际使用时替换为你的文件名列表即可
filenames = [
    "test_001_0.wav",
    "test_001_1.wav",
    "test_001_2.wav",
    "test_002_0.wav",
    "test_002_1.wav",
]

# 初始化默认值为0的字典,用来存各ID的索引总和
id_total = defaultdict(int)

for filename in filenames:
    parts = filename.split('_')
    file_id = parts[1]
    # 索引要转为整数再累加
    index = int(parts[-1].split('.')[0])
    id_total[file_id] += index

# 按要求格式输出
for file_id, total in id_total.items():
    print(f"total for test_{file_id}: {total}")

如果你不想引入额外依赖,也可以用普通字典实现:

id_total = {}
for filename in filenames:
    parts = filename.split('_')
    file_id = parts[1]
    index = int(parts[-1].split('.')[0])
    if file_id in id_total:
        id_total[file_id] += index
    else:
        id_total[file_id] = index

for file_id, total in id_total.items():
    print(f"total for test_{file_id}: {total}")

运行输出

total for test_001: 3
total for test_002: 2

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 12:48:01