-5

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.

Jérémie Bertrand
  • 3,025
  • 3
  • 44
  • 53
  • Im looking for a piece of code ??? SO is not a place where you can ask for complete code. Please give it a try then seek for help here on SO. – Tanveer Alam Jan 15 '15 at 09:58
  • CSV is basically a text file, you could parse that file easily with Python, take a look at https://docs.python.org/2/tutorial/inputoutput.html – Jaay Jan 15 '15 at 10:02
  • 1
    @Jaay and why should anybody parse the file by hand instead of simply using [the builtin csv library](https://docs.python.org/2/library/csv.html)? – l4mpi Jan 15 '15 at 10:29
  • @l4mpi I've been parsing CSV by hand several times, didn't even know there was a built-in function, tahnk for the tip ! – Jaay Jan 15 '15 at 10:32

1 Answers1

0

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.

Matthew Franglen
  • 4,441
  • 22
  • 32