Im looking for a piece of code that will print the average for each users score from a csv.
It needs to read all scores and then work out an average across the row for each users.
It also needs to calculate how many scores there are to accurately work out the average score so if there are only 2 tests completed it then needs divide by 2.
The CSV is
STUDENT,SCORE1,SCORE2,SCORE3
elliott,12,2,12
bob,0,11,1
test,0,1
I need the code to work out all users averages as described above in the CSV and then print the output.
Cheers.
解决方案
You can use the csv library to read the file. It is then just a case of calculating the averages:
import csv
with open('example.csv') as handle:
reader = csv.reader(handle)
next(reader, None)
for row in reader:
user, *scores = row
average = sum([int(score) for score in scores]) / len(scores)
print (
"{user} has average of {average}".format(user=user, average=average)
)
With your input this prints:
elliott has average of 8.666666666666666
bob has average of 4.0
test has average of 0.5
This code requires python 3.