Python如何将字典数据按10字符间距格式化输出为表格
解决方案
问题原因
原代码存在两个问题:
- 函数
printGrades内部代码缩进错误,运行会直接抛出语法异常 - 内层循环单独打印每门课程成绩,每次调用
print都会自动换行,导致成绩无法和姓名在同一行展示
修改后的完整代码
students = {('Ozols', 'Jānis'): {'Math': '10', 'ProgVal': '5', 'Sports': '5'}, ('Krumiņa', 'Ilze'): {'Math': '7', 'ProgVal': '3', 'Sports': '6'}, ('Liepa', 'Peteris'): {'Math': '3', 'ProgVal': '7', 'Sports': '7'}, ('Lapsa', 'Maris'): {'Math': '10', 'ProgVal': '10', 'Sports': '3'}} courses = ['Math', 'ProgVal', 'Sports'] def printGrades(): print("list of students:") print("{:10} {:10} {:10} {:10} {:10}".format('first', 'last', 'Math', 'ProgVal', 'Sports')) for lName, fName in students.keys(): studentRecord = students[(lName, fName)] # 按顺序拼接姓名、所有课程成绩,同一行输出 print("{:10} {:10} {:10} {:10} {:10}".format( fName, lName, studentRecord['Math'], studentRecord['ProgVal'], studentRecord['Sports'] )) while True: print() command = input("command:> ") command = command.lower() if command == 'print': printGrades() elif command == 'done': break print("DONE")
如果后续需要调整课程列表,不想硬编码课程名,可以把打印成绩的行替换为以下写法,修改courses列表时不需要调整打印逻辑,扩展性更强:
print(f"{fName:10} {lName:10} {' '.join(f'{studentRecord[c]:10}' for c in courses)}")
输出效果
输入print命令后,输出结果如下:
command:> print list of students: first last Math ProgVal Sports Jānis Ozols 10 5 5 Ilze Krumiņa 7 3 6 Peteris Liepa 3 7 7 Maris Lapsa 10 10 3 command:>
内容的提问来源于stack exchange,提问作者Muffin
相关产品推荐
相关产品推荐

