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
350 views
in Technique[技术] by (71.8m points)

python - Reading a CSV file, calculating averages and printing said averages

I have been assigned a task to create a quiz for primary school members. I have nailed every single task but this one.

I have to calculate the scores in the CSV file by: ? in alphabetical order with each student’s highest score for the tests ? by the highest score, highest to lowest ? by the average score, highest to lowest.

Here's the code I have so far. It doesn't seem to calculate the averages, even though I have followed the PowerPoint effectively. Everything in the PowerPoint is in the code.

Here's what I have so far:

import csv

results = open("Scores1.csv", "r+")
csv1 = csv.reader(results, delimiter=",")


data = []

for eachline in csv1:
    print(eachline)
    eachline[1] = int(eachline[1])
    eachline[2] = int(eachline[2])
    eachline[3] = int(eachline[3])
    highscore = max(eachline[1:4])
    eachline.append(highscore)
    average = round(sum(eachline[1:4])/3)
    eachline.append(average)
    data.append(eachline)

print(data)

The error I get is:

Traceback (most recent call last):
  File "Z:My WorkYear 11ComputingA453 Programming ProjectPythonFilesscores.py", line 17, in <module>
    eachline[1] = int(eachline[1])
IndexError: list index out of range

I don't understand the error being given to me, as everything in the CSV file looks fine. I aren't the best at it, and would like a simple answer please so I can understand it effectively and learn from it.

Many thanks.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Have a look at the pandas libary, for example, mean and max of rows can be can be obtained like this, but your example should be more precise, can't really see the exact structure of the csv file:

import pandas as pd

data = pd.read_csv("Scores1.csv")
data['mean']= data.mean(axis=1)
data['max'] = data.max(axis=1)

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

...