python - 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:
- which medicine majors made the honor roll and
- the average GPA of all the math majors
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
解决方案
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
推荐阅读
- python - 如何在变量中捕获单元测试的标准输出/标准错误?
- python - 我正在编写一个脚本来生成文件夹并使用shutil在Windows 10上的Python中将图像移动到它们,但它抛出了以下错误
- sql - 不知道如何得到一定的结果
- python - EXCEL 应用程序窗口未在 workbook.close() 上关闭
- angularjs - 如何刷新 AngularJS 组件中的数据以及绑定到其视图模型属性的组件中的数据?
- python - 如何获取特定日期是星期几?
- grails - Grails 分页:如何使用分页
- python - 如何在标记名称中包含感叹号的 XML 文件中查找元素?
- python - 如何将这些数据框与熊猫合并?
- angular - 如何改进此指令以显示带有 mat-error 的自定义错误