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

标签 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

最佳答案

您需要表示数据,当前您正在从读取文件中返回元组。 将它们存储在一个列表中,创建方法来过滤学生的专业,以及创建给定学生列表的平均 GPA 的方法。

您可能想让 GPA 在阅读时 float :

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 functions (浮点总和)

<小时/>
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

关于python - 计算混合文本文件中特定数字的平均值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53015900/

相关文章:

python - Pandas argmax() 弃用消息

python - 如果小数点前没有值,则加零(在 Python 2.7 中)

python - 为机器人设计 TCP/IP 命令接口(interface)

python-3.x - 为多个对象创建 TFrecord 文件

mysql - 如何计算每个全名的平均值并重复该值?

c++ - C++ 的平均、最大和最小赋值

python - 如果写入了 2 个文件,如何将最近的文件写入目录,程序应使用 python 检测到 2 个文件

python - 使用正则表达式以非贪婪方式匹配特定文本之前的文本

python - 如何计算特定字体和大小的字符串长度(以像素为单位)?

r - 如何在R中按小时计算变量的平均值