Reputation: 45
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
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