我有一个文本文件,上面有名字、学生的年级以及学生在考试中获得的分数。其格式如下:
John Doe 3 87
Jane Doe 4 89
Bob Smith 5 84
我需要找出三年级、四年级和五年级所有学生的平均数。这就是我所做的:
inFile = open("input.txt", "r", encoding = "utf8")
counter5 = 0
counter4 = 0
counter3 = 0
total5 = 0
total4 = 0
total3 = 0
for line in inFile:
if "5" in line:
total5 += int(line[-3:-1])
counter5 += 1
elif "4" in line:
total4 += int(line[-3:-1])
counter4 += 1
elif "3" in line:
total3 += int(line[-3:-1])
counter3 += 1
print(total5/counter5)
print(total4/counter4)
print(total3/counter3)
当然,问题是,在我的if语句中,有可能在考试分数中出现“3”、“4”或“5”,而不仅仅是分数级别。我相信有更简单的方法可以做到这一点。提前感谢您的帮助
正如建议的那样,这可以通过熊猫来实现
下面是如何使用熊猫解决这个问题
输入文件(Input.txt):
数据将存储在熊猫数据框中,如下所示:
各等级的平均值为:
您还可以提供:
将成绩和分数收集到一个dict中,循环并计算统计数据
见下文
in.txt
输出
您可以将该行拆分为令牌:
请注意,这是字符串,您需要根据自己的目的对其进行转换:
更完整的版本:
相关问题 更多 >
编程相关推荐