简体   繁体   English

对“ CSV”文件中的所有成绩进行平均的问题

[英]Troubles averaging all the grades from a “CSV” file

So I am new to python and I am having a hard time figuring this code. 因此,我是python的新手,我很难理解这段代码。 I am trying to use "CSV File" called exam_grades.csv and then write a function that reads in all my values in the file but using the string class split() method to split this long string into a list of strings. 我正在尝试使用名为“ exam_grades.csv”的“ CSV文件”,然后编写一个函数,该函数读取文件中的所有值,但使用字符串类split()方法将该长字符串拆分为字符串列表。 Each string represents a grade. 每个字符串代表一个成绩。 Then my function should return the average of all the grades. 然后,我的函数应返回所有年级的平均值。

So far this is what I have; 到目前为止,这就是我所拥有的; I can open the .csv file just fine but I'm having troubles averaging all the grades. 我可以很好地打开.csv文件,但在平均所有成绩时遇到了麻烦。 I have some commented out because I am sure where to go from what I have been doing :( 我有一些评论,因为我确定从我一直在做的事情中可以去:(

def fileSearch():
    'Problem 4'
    readfile = open('exam_grades.csv', "r")
    for line in readfile:
        l = line.split(str(","))
        #num_grades = len(l)
        #averageAllGrades = l * 500 
        #return num_grades
        print(l)
fileSearch()

Any advice? 有什么建议吗? Thanks! 谢谢!

Most CSV files have a header at the top, you'll want to skip that but for simplicity sake, let's say we ignore that. 大多数CSV文件的顶部都有一个标头,您可以跳过该标头,但是为了简单起见,假设我们忽略了该标头。

Here's some code that works: 这是一些有效的代码:

def fileSearch():
    'Problem 4'
    readfile = open('exam_grades.csv', "r")
    grade_sum = 0
    grade_count = 0
    for line in readfile:
        l = line.split(str(","))
        for grade in l:
            grade_sum += int(grade)
            grade_count += 1
    print(grade_sum/grade_count)

fileSearch()

This assumes you have multiple lines with grades and multiple grades per line. 假设您有多条分数线,每条线有多个分数。

We're keeping track of two variables here, the sum of all grades and the number of all grades we've added to the list (we're also casting to integers, since you're going to be reading strings). 我们在这里跟踪两个变量,即所有年级的总和以及我们添加到列表中的所有年级的数量(我们还将转换为整数,因为您将要读取字符串)。

When you add all the grades up and divide by the number of grades, you get an average. 当您将所有年级相加并除以年级数时,便得到一个平均值。

Hope this helped. 希望这会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM