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

2024-09-30 01:24:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个程序可以读取一个文件,其中包含学生名、ID、专业和GPA。你知道吗

例如(文件还有很多内容):

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

我得弄清楚:

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

我现在只有医学专业的荣誉榜。我不知道如何开始计算数学专业的平均绩点。如有任何帮助,我们将不胜感激。你知道吗

这是我目前拥有的代码:

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

Tags: 文件namereadlineenglish专业数学fileprint
1条回答
网友
1楼 · 发布于 2024-09-30 01:24:17

您需要表示数据,当前正在从读取文件返回元组。 将它们存储在一个列表中,创建方法来筛选你的专业学生,以及创建给定学生列表的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

相关问题 更多 >

    热门问题