A Bo
A Bo

Reputation: 45

Calculating an average score from a text file with names as well as numbers

I have created a text file that will hold a student's name as well as their grade in the format:

name1, 1
name2, 3
name3, 2
name1, 7
...

I have printed to the text file in the format:

file=open(studentclass+' Grades.txt', 'a')
file.write(name + ', ' + score + '\n')
file.close()

How would I calculate an average score for each name with Python using the score instead of the names?

Upvotes: 0

Views: 4162

Answers (1)

L3viathan
L3viathan

Reputation: 27283

This should work:

from collections import defaultdict
from itertools import chain

grades = defaultdict(list)
with open("Grades.txt") as f:
    for line in f:
        name, score = line.split(", ")
        grades[name].append(int(score))

for name in grades:
    print(name, sum(grades[name])/len(grades[name]), sep=": ")

print("Total average (student average):",
      sum(sum(grades[name])/len(grades[name]) for name in grades) / len(grades))
print("Total average (raw):",
      sum(chain.from_iterable(grades[name] for name in grades)) / sum(len(grades[name]) for name in grades))

edit: Changed to meet requirements of per-student averages.

edit: Added global averages.

Upvotes: 1

Related Questions