读入一个包含多个等级的文件,每个等级用逗号分隔,并打印出计算出的平均值

Read in a file that has multiple grades, each separated by a comma, and prints out the computed average

问题:完成以下程序,它读入一个包含多个成绩的文件,每个成绩用逗号分隔,并打印出计算出的平均值。即写函数getGrades():calculateAverage():

def main():
  grades = getGrades()   #get the file name containing the grades
                         #and return the contents of the file
  avg = calculateAverage(grades) #separate the grades into numbers and compute
                         #the average
  print("The calculated average is:", avg)
main()

我已经插入了给定的函数并编写了一个新程序,但是我有点困惑,而且我也遇到了错误。请帮忙!

def getGrades():
  filename = input("Please enter a file name: ")
  openfile = open(filename, "r")
  readfile = openfile.readlines()

  return readfile

def calculateAverage(n):
  totalGrades = []

  for i in (n):
    Split = list(map(int, i.split(",")))
    totalGrades += Split

  avg = sum(totalGrades)/float(len(totalGrades))

  return avg

def main():
  grades = getGrades()                  
  avg = calculateAverage(grades) 
  print("The calculated average is:", avg)
main()

在你的 calculateAverage() 函数中,你传递参数 n 但对于 for 循环你使用函数 getGrades() 的局部变量名称 readfile .

还有split is a list of strings. To convert them to integers to perform the summations you can use map()的结果。 map returns 一个迭代器,它将函数应用于可迭代的每个项目,产生结果。

要从您阅读的行中删除换行符和其他空格,您可以使用 rstrip().

最后,如果您的两个参数都是整数,要执行浮点除法,您必须将两者之一转换为 float。检查这个 answer.

最终程序如下所示:

def getGrades():
  filename = input("Please enter a file name: ")
  openfile = open(filename, "r")
  readfile = openfile.readlines()

  return readfile

def calculateAverage(n):
  total_grades = []
  for i in (n):
    line_grade = list(map(int, i.rstrip().split(",")))
    total_grades += line_grade
  avg = sum(total_grades)/float(len(total_grades))
  return avg

def main():
  grades = getGrades()                  
  avg = calculateAverage(grades) 
  print("The calculated average is:", avg)

if __name__ == "__main__":
  main()

如果您 运行 使用包含以下内容的测试文件: 5,10,15,20 你得到:

>>> 
Please enter a file name: test.txt
The calculated average is: 12.5
>>> 

calculateAverage(n) 没有 map() 而有 list comprehensions 可以是:

def calculateAverage(n):
  total_grades = []
  for i in (n):
    line_grade = i.rstrip().split(",")
    line_grade = [int(x) for x in line_grade]
    total_grades += line_grade
  avg = sum(total_grades)/float(len(total_grades))
  return avg

最后你可以用简单的方式来做,并有一个 for 循环来将 split 返回的列表中的每个元素转换为整数:

def calculateAverage(n):
  total_grades = []
  for i in (n):
    line_grade = i.rstrip().split(",")
    for element in line_grade:
      total_grades.append(int(element))
  avg = sum(total_grades)/float(len(total_grades))
  return avg