高仿模拟练习,完整编写程序并运行出结果,答案点击按钮展开
文件 score.txt 中每行一个学生的分数(整数),读取所有分数计算平均分,保留 2 位小数输出到屏幕。
# 文件 score.txt 内容示例:
# 85
# 90
# 78
# 请在下面编写完整程序
with open("score.txt") as f:
scores = [int(line.strip()) for line in f if line.strip()]
avg = sum(scores) / len(scores)
.2f}".format(avg))
列表推导式逐行读取并转 int,strip 去空白;sum/len 求平均,{:.2f} 保留两位小数。示例输出 84.33。