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

如何在Python中用字典计算文本文件内各名称的累计总和?

解决名称累计总和计算问题

你的代码目前已经能正确提取名称集合和地点集合,但缺少分数累加的核心逻辑。这里直接给你修改后的完整代码,并说明关键调整点:

name_set = set() 
location_set = set()
userfile = input("请输入文件名:") 
# 使用with语句自动管理文件,无需手动关闭
with open(userfile, "r") as input_file2:
    input_file = input_file2.readlines()

# 提取第一行的名称,去除每个名称前后的空格
names = [n.strip() for n in input_file[0].strip().split(',')]
name_set.update(names) 

# 初始化累计字典,每个名称的初始总分设为0
name_to_num = {name: 0 for name in names}

# 从第二行开始遍历(跳过第一行的名称列表)
for line in input_file[1:]:  
    line = line.strip()
    if not line:  # 跳过空行
        continue
    if line.startswith('Location'): 
        # 提取地点名称,去除前后空格
        location = line.split(":")[-1].strip()
        location_set.add(location)
    else:
        # 处理分数记录行,拆分名称和分数并去除空格
        parts = [p.strip() for p in line.split(',')]
        name = parts[0]
        score = int(parts[1])
        # 累加当前分数到对应名称的总分
        name_to_num[name] += score

# 按要求格式输出结果
print(f"name_set = {{{', '.join(name_set)}}} location_set = {{{', '.join(location_set)}}}")
print("生成映射名称到累计总和的字典:")
print(f"dic = {name_to_num}")

关键调整说明

  • 用with语句打开文件:自动处理文件关闭,比直接open更安全规范
  • 初始化累计字典:提前给每个名称设置初始值0,确保后续能正常累加
  • 遍历逻辑优化:从第二行开始遍历,跳过空行,区分地点行和分数行
  • 分数累加:识别分数行后,拆分出名称和分数(转成整数),累加到对应名称的数值上

运行这段代码后,就能得到你预期的结果:名称集合、地点集合,以及每个名称的累计总分字典。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 00:40:59