[英]Calculate the average of grades in a file. it should return None if file doesn't exist and 0.0 if it doesn't contain any grades
输入(这是文件 mygrades.txt 包含的内容)
CS1:5.75
#
CS 2:5.5
数学 1:5.75
@!
经济 1:5.5
物理:6
化学:5.75
!#
@
输出:5.70
代码:
import os
def get_average_grade(path):
grades = []
filesize = os.path.getsize("C:\\Users\Documents\mygrades.txt")
if not os.path.exists(path):
return None
with open("C:\\Users\Documents\mygrades.txt", "r") as f:
filesize = os.path.getsize("C:\\Users\Documents\mygrades.txt")
if filesize == 0: # not entirely correct because it might contain "#@$%$^&^&*^" for example which means no grade but wont return 0.0
return 0.0
else:
for line in f.readlines():
if ":" in line:
searchforcolon = line.find(":")
number1 = float(line[searchforcolon + 1:])
grades.append(number1)
average = sum(grades)/len(grades)
return average
print(get_average_grade("C:\\Users\Documents\mygrades.txt"))
您的代码的以下表达可以完成这项工作。 我假设您想将平均值四舍五入到小数点后第二位:
v = []
with open(PATH_TO_FILE, "r") as f:
for l in f.readlines():
if ":" in l:
v.append(float(l.split(":")[1].strip()))
print(f'{int(100 * sum(v)/len(v))/100:.2f}' if len(v) > 0 else None)
似乎你想要这样的东西:
import os
def get_average_grade(path):
if not os.path.exists(path):
return None
grades = []
with open(path) as file:
for line in file:
if ':' in line:
_, grade = line.strip().split(':')
if ''.join(grade.strip().split('.', maxsplit=1)).isnumeric():
grades.append(float(grade))
return (grades and round(sum(grades) / len(grades), 2)) or 0.0
print(get_average_grade('myfile.txt'))
首先,您没有在函数中正确使用path
参数,您必须将它放在使用路径的任何地方。
这个函数的工作非常简单,首先检查路径是否存在,如果不返回 None。 然后定义一个列表并打开文件(使用for line in f
而不是for line if f.readlines()
)。 然后检查分号是否在该行中并由该分号拆分,而不是尝试查找其索引,这将返回一个列表,该列表将包含该行中每个分号前后的文本。 因此,通过使用解包来提取等级,然后检查它是否可以转换为浮点数,如果不可能,则只需继续(如果无法转换为浮点数,您可能希望以某种方式提醒用户)。 然后有一个简单的短路,首先检查成绩列表是否为空,如果是,则返回0.0
(因此未找到成绩),否则返回四舍五入到小数点后两位的平均值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.