基于文本文件构建世界杯冠军嵌套字典及格式化输出问题求助
修正世界杯冠军嵌套字典构建与格式化输出代码
原代码核心问题
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()
关键优化说明
- 文件资源管理:使用
with语句自动关闭文件,避免资源泄漏 - 表头处理:通过
next(file)跳过第一行表头数据 - 嵌套字典构建:
- 检查国家是否已存在,存在则累加夺冠次数并追加记录
- 新国家直接初始化嵌套字典,存储次数、年份列表、队长列表、教练列表
- 最终将列表转为逗号分隔字符串,方便输出展示
- 输出格式化:
- 用对齐符号
<保证各列内容对齐 - 添加分隔线提升可读性
- 按国家名称排序后输出
- 用对齐符号
内容的提问来源于stack exchange,提问作者Yeonari
相关产品推荐
相关产品推荐

