我有一个程序可以读取包含学生姓名、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 comprehensions和 Built 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/