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

Python从文件生成集合、映射字典及计算总和的技术问题

问题描述

需求:使用Python从指定格式的文件中生成两个集合name_set = { A, B, C }、location_set = {London, Amsterdam, Paris},同时生成姓名到数字的映射记录并计算每个姓名的数值总和。

输入文件示例:

A, B, C 
Location:London 
A, 46
B, 93
C, 32
Location:Amsterdam 
A, 83
B, 21
C, 92
Location:Paris
A, 29
B, 91
C, 10

期望输出:

name_set = { A, B, C }
location_set = {London, Amsterdam, Paris}
dic = {A: 46, B: 93, C:32 , A: 83, B: 21, C: 92, A:29, B: 91, C:10}
A has 158 
B has 205 
C has 134 

原代码无法得到预期结果,代码如下:

name_set = set() 
location_set = set()
num_set = set ()
userfile = input("Enter input file name:") 
input_file2 = open(userfile, "r") 
input_file = input_file2.readlines()
name_set = input_file[0].strip().split(',')

for next_line in input_file: 
    if next_line.startswith("Location"):
        location_set = next_line.strip().split(":")[-1]
    else:
       num_set = next_line.strip().split(',')[-1]
print(name_set) 
print(location_set) 
print(num_set)

name_to_num = {} 
for k in name_set:
   for v in scores_set:
      party_to_score[k] = v
print(name_to_num) 

错误分析与修正代码

原代码问题点

  1. 集合赋值错误:name_set被赋值为列表而非集合,拆分后元素带空格;location_set每次被覆盖为单个字符串,未添加到集合中
  2. 数值收集错误:num_set仅保留最后一行数值,后续还用到未定义的scores_set
  3. 字典逻辑错误:变量名写错(party_to_score未定义),嵌套循环逻辑完全错误,无法映射姓名与数值并累加
  4. 文件资源未释放:直接打开文件未关闭,存在资源泄漏风险

修正后的代码

name_set = set()
location_set = set()
# 存储所有姓名-数值对
name_records = []
# 存储每个姓名的数值总和
name_total = {}

userfile = input("Enter input file name:")
# 使用with语句自动管理文件资源,避免泄漏
with open(userfile, "r") as input_file:
    lines = input_file.readlines()
    # 处理第一行的姓名,转为集合并去除空格
    first_line = lines[0].strip()
    names = [name.strip() for name in first_line.split(',')]
    name_set.update(names)
    # 初始化总和字典
    for name in names:
        name_total[name] = 0

    # 遍历剩余行处理地点和数值
    for line in lines[1:]:
        line = line.strip()
        if not line:
            continue  # 跳过空行
        if line.startswith("Location"):
            # 提取地点并添加到集合
            loc = line.split(":")[-1].strip()
            location_set.add(loc)
        else:
            # 提取姓名和数值,转换为整数
            parts = [p.strip() for p in line.split(',')]
            if len(parts) == 2:
                name, num = parts
                num = int(num)
                name_records.append((name, num))
                # 累加数值总和
                name_total[name] += num

# 按要求格式输出集合
print(f"name_set = {{{', '.join(name_set)}}}")
print(f"location_set = {{{', '.join(location_set)}}}")

# 模拟期望的dic格式(注意:Python字典键唯一,无法重复,此处用字符串拼接展示所有记录)
dic_str = "dic = {"
for idx, (name, num) in enumerate(name_records):
    if idx > 0:
        dic_str += ", "
    dic_str += f"{name}: {num}"
dic_str += "}"
print(dic_str)

# 输出每个姓名的数值总和
for name, total in name_total.items():
    print(f"{name} has {total}")

关键说明

  1. 集合处理:第一行拆分后去除每个姓名的空格,用update()添加到name_set;地点用add()方法添加到location_set,避免覆盖
  2. 数值处理:用列表name_records存储所有姓名-数值对,同时用name_total字典实时累加每个姓名的总和
  3. 格式兼容:由于Python字典键唯一,无法存在重复的A/B键,因此通过字符串拼接模拟期望的dic格式;若需保留所有记录,建议用列表存储元组

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 10:05:21