简体   繁体   中英

Sum values in a text file from multiple lines (python)

I'm trying to sum values of quiz scores from a text file. I need to sum all of the quiz score values from every person to find the class average for quiz scores. So far my program will sum the scores for each line, but it does not sum each line together. How do I sum each line together? This is my text file with each person on one line (10 people total)

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)

outputs:

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

I want this to add 250 + 220 + ... + 240

Just create another variable and add the contents of variable d to that variable for each iteration. Finally print the created temporary variable at the last( next to the for loop ).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM