我正在尝试从文本文件中对测验分数的值求和。我需要将每个人的所有测验得分值相加,以找到测验得分的班级平均值。到目前为止,我的程序将对每一行的分数求和,但它不会将每一行相加。如何将每一行相加?这是我的文本文件,每个人在一行(总共10人)
Aenci, Iaron; 0905229; Quizzes 90%, 90%, 70%; Individual projects 80%, 70%, 90%; Labs 80%, 80%, 90%; Midterm 90%; Group Projects 90%, 80%, 70%; Final 90% Yarton, Nabrina; 0908843; Quizzes 90%, 60%, 70%; Individual projects 90%, 70%; Labs 80%, 80%, 90%; Midterm 90%; Group Projects 90%, 80%, 70%; Final 90% Jayer, Rody; 0908845; Quizzes 90%, 70%, 80%; Individual projects 90%, 60%, 50%; Labs 30%, 70%, 80%; Midterm 90%; Group Projects 90%, 70%, 80%; Final 80%
def cc_quiz(file):
for line in open(file):
student_list = line.split()
count = len(student_list)
a = str(student_list)
start_position = a.find('Quizzes')
end_position = a.find('Individual')
class_quiz = a[start_position + 8: end_position - 3]
cq = class_quiz.replace('%', '')
cq1 = cq.replace(',', '')
cq2 = cq1.replace(';', '')
cq3 = cq2.replace("'", '')
c = cq3.split()
d = sum(float(x) for x in c)
print(d)
输出:
250.0
0
220.0
0
240.0
0
120.0
0
250.0
0
220.0
0
240.0
0
250.0
0
220.0
0
240.0
我想要添加250 + 220 + ... + 240
答案 0 :(得分:0)
只需创建另一个变量,并将变量d
的内容添加到每个迭代的变量中。最后在最后打印创建的临时变量(for循环旁边的 )。
def cc_quiz(file):
su = 0
for line in open(file):
student_list = line.split()
count = len(student_list)
a = str(student_list)
start_position = a.find('Quizzes')
end_position = a.find('Individual')
class_quiz = a[start_position + 8: end_position - 3]
cq = class_quiz.replace('%', '')
cq1 = cq.replace(',', '')
cq2 = cq1.replace(';', '')
cq3 = cq2.replace("'", '')
c = cq3.split()
d = sum(float(x) for x in c)
su += d
print su