Python 函数详解:使用 format 格式化输出学生信息表格
def show_query(lst):
'''
将学生信息列表以表格形式打印出来。
Args:
lst: 包含学生信息的列表,每个元素是一个字典,
包含 'id', 'name', 'english', 'python', 'java' 键。
'''
if len(lst) == 0:
print('无相关信息')
return
# 定义标题显示格式
format_title = '{:^6}\t{:^12}\t{:^8}\t{:^10}\t{:^10}\t{:^8}'
print(format_title.format('ID', '姓名', '英语成绩', 'python成绩', 'Java成绩', '总成绩'))
# 定义内容显示格式
format_data = '{:^6}\t{:^12}\t{:^8}\t{:^10}\t{:^10}\t{:^8}'
for item in lst:
total_score = int(item.get('english', 0)) + int(item.get('python', 0)) + int(item.get('java', 0))
print(format_data.format(item.get('id'),
item.get('name'),
item.get('english'),
item.get('python'),
item.get('java'),
total_score
))
这段代码定义了一个名为 show_query 的函数,用于将学生信息以表格的形式打印出来。
代码解析:
- 函数定义和文档字符串:
def show_query(lst):定义了一个名为show_query的函数,并接受一个参数lst。- 文档字符串
'''...'''解释了函数的作用和参数类型。
- 检查列表是否为空:
if len(lst) == 0:: 检查传入的列表是否为空。- 如果为空,打印 '无相关信息' 并使用
return结束函数执行。
- 定义标题格式:
format_title = '{:^6}\t{:^12}\t{:^8}\t{:^10}\t{:^10}\t{:^8}': 定义了标题行的格式,使用分隔符创建多个列,{:^}用于设置居中对齐,数字表示列宽。print(format_title.format('ID', '姓名', '英语成绩', 'python成绩', 'Java成绩', '总成绩')): 使用format方法填充标题内容并打印。
- 定义内容格式:
format_data = '{:^6}\t{:^12}\t{:^8}\t{:^10}\t{:^10}\t{:^8}': 定义了数据行的格式,与标题格式相同。
- 遍历学生信息并打印:
for item in lst:: 使用循环遍历lst中的每个学生信息字典。total_score = int(item.get('english', 0)) + int(item.get('python', 0)) + int(item.get('java', 0)): 计算每个学生的总成绩,使用get方法避免键不存在的错误。print(format_data.format(item.get('id'),...)): 使用format方法填充数据内容并打印每一行学生信息。
改进:
- 添加了函数文档字符串,提高代码可读性。
- 在计算总成绩时,使用
get方法并设置默认值为 0,避免了因数据缺失导致的错误。 - 使用更具有描述性的变量名
total_score。
这段代码清晰地展示了如何使用 Python 的 format 方法格式化输出数据,使其更易于阅读和理解。
原文地址: https://www.cveoy.top/t/topic/f3tu 著作权归作者所有。请勿转载和采集!