题目:
从文本文件逐行读入某个班级的百分制成绩序列,计算基本统计值(最大值、最小值、平均值、标准差、中位数),并统计成绩在不同区间([0, 59]、[60,69]、[70,79]、[80,89]、[90,100])的累计数量和百分比。除累计数量外,其他输出保留小数点后两位。并将统计结果存入文本文件中
思路:
主要考察了对python读取文件和写入文件的使用方法
代码:
stu = []
def get_file(file_path):
fo = open(file_path, "r")
while True:
line = fo.readline()
if len(line) == 0:
break
stu.append(float(line.strip('\n')))
def calculate(file_path):
fo = open(file_path, "a+")
stu.sort()
fo.write("\n")
fo.write("最小值:{}\n".format(round(stu[0]), 2))
stu.sort(reverse=True)
fo.write("最大值:{}\n".format(round(stu[0]), 2))
avg = sum(stu)/len(stu)
fo.write("平均值:{}\n".format(round(avg, 2)))
# 计算标准差
s = 0
for i in stu:
s = s + (i-avg)*(i-avg)
s = s / len(stu)
s = pow(s, 0.5)
fo.write("标准差:{}\n".format(round(s, 2)))
# 计算中位数
stu.sort()
med = stu[len(stu) // 2]
if len(stu) % 2 == 0:
med = (med + stu[(len(stu)//2) + 1]) / 2
fo.write("中位数:{}\n".format(round(med, 2)))
# 计算分数段占比
count = [0, 0, 0, 0, 0]
for i in stu:
if i < 60:
count[0] += 1
elif i < 70:
count[1] += 1
elif i < 80:
count[2] += 1
elif i < 90:
count[3] += 1
elif i < 100:
count[4] += 1
fo.write("[0, 59]累计数量{},百分比{}\n".format(count[0], round(count[0]/len(stu), 2)))
fo.write("[60, 69]累计数量{},百分比{}\n".format(count[1], round(count[1] / len(stu), 2)))
fo.write("[70, 79]累计数量{},百分比{}\n".format(count[2], round(count[2] / len(stu), 2)))
fo.write("[80, 89]累计数量{},百分比{}\n".format(count[3], round(count[3] / len(stu), 2)))
fo.write("[90, 100]累计数量{},百分比{}\n".format(count[4], round(count[4] / len(stu), 2)))
fo.close()
print("Done")
file_path = input("请输入文件地址:")
get_file(file_path)
calculate(file_path)