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

基于文本文件构建世界杯冠军嵌套字典及格式化输出问题求助

修正世界杯冠军嵌套字典构建与格式化输出代码

原代码核心问题

  • createDict函数逻辑混乱:
    • 每次循环重置对应国家的嵌套字典,导致之前的夺冠记录被覆盖
    • 错误将Wins等字段放在外层字典,而非对应国家的嵌套结构内
    • 无意义的word == dict[line[1]]判断,永远无法触发(字典不可能等于字符串)
  • 未跳过文件表头,会把表头行当作数据处理
  • 未处理多次夺冠的情况,无法存储同一国家的多组年份、队长、教练信息

修正后的完整代码

def main():
    with open('world_cup_champions.txt', 'r') as inFile:
        champions = createDict(inFile)
    printChamps(champions)

def createDict(file):
    champions_dict = {}
    # 跳过表头行
    next(file)
    try:
        for line in file:
            line = line.strip().split(",")
            if len(line) != 4:
                continue  # 跳过格式错误的行
            year, country, coach, captain = line
            # 处理已存在的国家
            if country in champions_dict:
                champions_dict[country]['Wins'] += 1
                champions_dict[country]['Year(s)'].append(year)
                champions_dict[country]['Captain'].append(captain)
                champions_dict[country]['Coach'].append(coach)
            else:
                # 初始化新国家的嵌套字典
                champions_dict[country] = {
                    'Wins': 1,
                    'Year(s)': [year],
                    'Captain': [captain],
                    'Coach': [coach]
                }
        # 将列表转为逗号分隔字符串,适配输出格式
        for country in champions_dict:
            champions_dict[country]['Year(s)'] = ', '.join(champions_dict[country]['Year(s)'])
            champions_dict[country]['Captain'] = ', '.join(champions_dict[country]['Captain'])
            champions_dict[country]['Coach'] = ', '.join(champions_dict[country]['Coach'])
        return champions_dict
    except Exception as e:
        print(f"文件处理出错: {e}")
        return {}

def printChamps(unsorted_dict):
    # 打印格式化表头
    print(f"{'Country':<10} {'Wins':<5} {'Year(s)':<32} {'Captain':<72} {'Coach':<30}")
    print("-" * 150)
    # 按国家名称排序输出
    sorted_dict = dict(sorted(unsorted_dict.items()))
    for country, info in sorted_dict.items():
        print(f"{country:<10} | {info['Wins']:<5} | {info['Year(s)']:<32} | {info['Captain']:<72} | {info['Coach']:<30}")

if __name__ == '__main__':
    main()

关键优化说明

  1. 文件资源管理:使用with语句自动关闭文件,避免资源泄漏
  2. 表头处理:通过next(file)跳过第一行表头数据
  3. 嵌套字典构建:
    • 检查国家是否已存在,存在则累加夺冠次数并追加记录
    • 新国家直接初始化嵌套字典,存储次数、年份列表、队长列表、教练列表
    • 最终将列表转为逗号分隔字符串,方便输出展示
  4. 输出格式化:
    • 用对齐符号<保证各列内容对齐
    • 添加分隔线提升可读性
    • 按国家名称排序后输出

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 21:05:19