2015-04-18 38 views
0

我正在嘗試總結文本文件中測驗分數的值。我需要總結每個人的所有測驗分數值,以找出測驗分數的平均分數。到目前爲止,我的程序將總結每行的分數,但不會將每行累加在一起。我如何將每條線彙總在一起?這是每個人在一行我的文本文件(10人)來自多行的文本文件中的總和值(python)

 
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'值。 – jedwards

回答

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 
+0

它工作!非常感謝! – arl6

相關問題