首页 > 解决方案 > Calculating the average of specific numbers in a mixed text file?

问题描述

I have a program that reads a file that has student names, IDs, majors, and GPAs in it.

For example (there is much more to the file):

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

I have to figure out:

All I have right now is the list of medicine majors that made honor roll. I have no idea how to start calculating the average GPA of math majors. Any help is appreciated, and thanks in advance.

This is the code I currently have:

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":

Here is the students6.py file that is being imported:

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

标签: pythonpython-3.xaverage

解决方案


You need to represent the data, currently you are returning tuples from reading the file. Store them in a list, create methods to filter your students on theire major and one that creates the avgGPA of a given student-list.

You might want to make the GPA a float on reading:

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

Two new helper methods that work on the returned student-data-tuples:

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

Main prog:

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))

Output:

# 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

See: PyTut: List comprehensions and Built in functions (float, sum)


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

prettyPrint(engl)

Output:

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

推荐阅读