计算学生平均成绩时忽略特定字母成绩

时间:2021-04-02 06:32:07

标签: python

我正在尝试计算取 [0]=14224 的学生的数字成绩的平均值。但是我如何告诉我的程序忽略任何带有“W”的成绩?

import sys
import csv


def findnumericgrade(grade):
    if grade == 'A':
        return 4.0
    elif grade == 'B':
        return 3.0
    else:
        return 2.0


def loaddata(filename, course):
    count = 0
    total = 0.0
    with open(filename, 'r') as f:
        lines = csv.reader(f)
        next(lines)
        for row in lines:
            if course in row[0]:
                get_grade = findnumericgrade(row[3])
                total += float(get_grade)
                count += 1
        avg = total / count
    print(f"The {course} average is: {round(avg, 2)}")


loaddata('studentdata.csv', sys.argv[1])

#studentdata.csv 示例: enter image description here

2 个答案:

答案 0 :(得分:3)

当然有很多方法。最简单的方法可能只是检查“W”字符串并继续下一行。

执行此操作的一种方法是使用 continue 控件移动到循环中的下一次迭代。

def loaddata(filename, course):
    count = 0
    total = 0.0
    with open(filename, 'r') as f:
        lines = csv.reader(f)
        next(lines)
        for row in lines:
            if row[3] == 'W':
                continue  # Go to next iteration in loop
            if course in row[0]:
                get_grade = findnumericgrade(row[3])
                total += float(get_grade)
                count += 1
        avg = total / count
    print(f"The {course} average is: {round(avg, 2)}")

您也可以通过将 if 语句设为 and boolean operation 来确保 Course_Grade 不是“W”。

def loaddata(filename, course):
    count = 0
    total = 0.0
    with open(filename, 'r') as f:
        lines = csv.reader(f)
        next(lines)
        for row in lines:
            if course in row[0] and row[3] != 'W':
                get_grade = findnumericgrade(row[3])
                total += float(get_grade)
                count += 1
        avg = total / count
    print(f"The {course} average is: {round(avg, 2)}")

上述解决方案可能是最实用的,因为这看起来像是某种实用程序脚本,但是根据您期望的数据集有多大,您可以使用类似 pandas 的内容。然后您就可以使用它提供的所有数据操作和分析工具。

import sys
import pandas as pd


def find_numeric_grade(grade):
    if grade == 'A':
        return 4.0
    elif grade == 'B':
        return 3.0
    else:
        return 2.0


df = pd.read_csv('studentdata.csv')
section_number = int(sys.argv[1])

print(df[(section_number == df['Section_Number']) & (df['Course_Grade'] != 'W')]
      ['Course_Grade'].apply(find_numeric_grade).mean())

*使用 studentdata.csv

中的以下数据测试的解决方案
Section_Number,Prof_ID,Student_ID,Course_Grade,Student_Name,Course_ID
14224,5,109,B,John Smith,IT1130
14224,5,110,B,Jennifer Johnson,IT1130
14224,5,111,W,Kristen Hawkins,IT1130
14224,5,112,A,Tom Brady,IT1130
14224,5,113,C,Cam Newton,IT1130
14224,5,114,C,Tim Tebow,IT1130
14225,5,115,A,Peyton Manning,IT1130
14225,5,116,B,Maria Sharapova,IT1130
14225,5,117,W,Brian McCoy,IT1130

答案 1 :(得分:0)

 if course in row[0]:
     if row[3]!='W':
          get_grade = findnumericgrade(row[3])
          total += float(get_grade)
          count += 1
      avg = total / count