Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

Row Average CSV Python

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...