我正在尝试编写一个程序来读取3个类数据文件,例如period1.txt,period2.txt。这些文件中包含3个不同学生的名字,姓氏和3个考试成绩。
数据文件的格式如下所示
Meagan. Hesse. 99. 99. 99
我的程序然后假设取平均分配并将结果和学生姓名写在另一个txt文件夹中,例如period1cgrade和period2grade
我已经尝试修复一些问题,但看起来它仍在进行中我还不确定我是否正确打开数据文件,你能不看一下那部分
def calcaverage(test1,test2,test3):
for count in range(test1,test2,test3):
curraverage=0
curraverage=((test1[count]+ test2[count]+ test3[count])/3)
currentaverage.append(curraverage)
if curraverage>= 90:
grade= "A"
lettergrades.append(grade)
elif curraverage >= 80 and curraverage < 90:
grade= "B"
lettergrades.append(grade)
elif curraverage >= 70 and curraverage < 80:
grade= "C"
lettergrades.append(grade)
elif curraverage < 70:
grade= "F"
lettergrades.append(grade)
name=[]
test1=[]
test2=[]
test3=[]
averagescore=[]
lettergrades=[]
with open ("period1.txt", 'r') as infile:
for line in infile:
values = line.split()
name.append(values[0] + ','+ values[1])
for line in infile:
values = line.split()
score1=float(values[2])
test1.append(score1)
for line in infile:
values = line.split()
score2=float(values[3])
test2.append(score2)
for line in inline:
values = line.split()
score3=float(values[4])
test3.append(score3)
averagescore=calcaverage(test1,test2,test3)
print(line)
答案 0 :(得分:1)
有人已经提交了答案,但在我看来,这是做你想做的最干净的方法......
marks = {90:'A', 80:'B', 70:'C', 0:'F'}
grades = {}
def calc_grades(infile):
with open(infile, 'r') as f:
for line in f.read().splitlines():
fname, lname, g1, g2, g3 = line.split('. ')
avg = sum(map(float, [g1, g2, g3]))/3
name = "%s %s" % (fname, lname)
grades[name] = marks[min(marks.keys(), key=lambda k: abs(k-avg) if avg>=k else 100)]
def put_grades(outfile):
with open(outfile, 'w+') as f:
f.writelines(["%s: %s\n" % (k, v) for k, v in grades.items()])
if __name__ == "__main__":
calc_grades('period1.txt')
put_grades('p1_grades.txt')
编辑:修正了lambda表达式
答案 1 :(得分:0)
这里我将如何做到这一点:
FILENAMES = [("period1.txt", "period1grade.txt"), ... ]
for inpath, outpath in FILENAMES:
with open(inpath) as infile, open(outpath, 'w') as outfile:
for line in infile:
if line:
first, last, grades* = map(str.strip,line.split('.'))
grades = map(int, grades) # maybe float?
output = "{}. {}. {}\n".format(first, last, sum(grades)/len(grades)
outfile.write(output)
我现在看到你必须指定一个字母等级,所以我会像你一样做,并为此写一个单独的函数
def getlettergrade(grades):
"""Returns a letter grade ["A","B","C","F"] given a list of ints as grades of 100"""
percent = sum(grades)/len(grades)
if grade >= 90: return "A"
elif grade >= 80: return "B"
elif grade >= 70: return "C"
else: return "F"