计算混合文本文件中特定数字的平均值?

时间:2018-10-26 20:26:59

标签: python python-3.x average

我有一个程序,该程序读取具有学生名称 ID 专业 GPA 的文件在里面。

例如(文件有更多内容):

OLIVER
8117411
English
2.09
OLIVIA
6478288
Law
3.11
HARRY
5520946
English
1.88
AMELIA
2440501
French
2.93

我必须弄清楚:

  • 哪些医学专业获得了荣誉榜,
  • 所有数学专业的平均GPA

我现在所拥有的是名列榜首的医学专业名单。我不知道如何开始计算数学专业的平均GPA。感谢您的帮助,在此先感谢。

这是我当前拥有的代码:

import students6

file = open("students.txt")

name = "x"
while name != "":
    name, studentID, major, gpa = students6.readStudents6(file)
    print(name, gpa, major, studentID)

    if major == "Medicine" and gpa > "3.5":
        print("Med student " + name + " made the honor roll.")

    if major == "Math":

这是要导入的 students6.py 文件:

def readStudents6(file):
    name = file.readline().rstrip()
    studentID = file.readline().rstrip()
    major = file.readline().rstrip()
    gpa = file.readline().rstrip()
    return name, studentID, major, gpa

1 个答案:

答案 0 :(得分:1)

您需要表示数据,当前您正在从读取文件返回元组。 将它们存储在列表中,创建方法以过滤您所学专业的学生,​​并创建创建给定学生列表的avgGPA的方法。

您可能希望使GPA浮动阅读:

with open("s.txt","w") as f:
    f.write("OLIVER\n8117411\nEnglish\n2.09\nOLIVIA\n6478288\nLaw\n3.11\n" + \
            "HARRY\n5520946\nEnglish\n1.88\nAMELIA\n2440501\nFrench\n2.93\n")

def readStudents6(file):
    name = file.readline().rstrip()
    studentID = file.readline().rstrip()
    major = file.readline().rstrip()
    gpa = float(file.readline().rstrip())  # make float
    return name, studentID, major, gpa

对返回的学生数据元组起作用的两种新的辅助方法:

def filterOnMajor(major,studs):
    """Filters the given list of students (studs) by its 3rd tuple-value. Students
    data is given as (name,ID,major,gpa) tuples inside the list."""
    return [s for s in studs if s[2] == major] # filter on certain major

def avgGpa(studs):
    """Returns the average GPA of all provided students. Students data
    is given as (name,ID,major,gpa) tuples inside the list."""
    return sum( s[3] for s in studs ) / len(studs) # calculate avgGpa

主要编:

students = []

with open("s.txt","r") as f:
    while True:
        try: 
            stud = readStudents6(f)
            if stud[0] == "":
                break
            students.append( stud )
        except:
            break


print(students , "\n")

engl = filterOnMajor("English",students)

print(engl, "Agv: ", avgGpa(engl))

输出:

# all students    (reformatted)
[('OLIVER', '8117411', 'English', 2.09), 
 ('OLIVIA', '6478288', 'Law', 3.11), 
 ('HARRY', '5520946', 'English', 1.88), 
 ('AMELIA', '2440501', 'French', 2.93)] 

# english major with avgGPA    (reformatted)
[('OLIVER', '8117411', 'English', 2.09), 
 ('HARRY', '5520946', 'English', 1.88)] Agv:  1.9849999999999999

请参阅:PyTut: List comprehensionsBuilt in functionsfloatsum


def prettyPrint(studs):
    for name,id,major,gpa in studs:
        print(f"Student {name} [{id}] with major {major} reached {gpa}")

prettyPrint(engl)

输出:

Student OLIVER [8117411] with major English reached 2.09
Student HARRY [5520946] with major English reached 1.88