Python 学生信息处理:读取文件、创建对象、计算总分
"Python 学生信息处理:读取文件、创建对象、计算总分"\n本教程展示如何使用 Python 读取包含学生信息的文件,将信息转换成学生对象,并计算所有学生的总分。使用 Student 类来表示学生对象,并通过文件操作和数据处理技巧实现功能。\n\npython\n# 定义 Student 类\nclass Student:\n def __init__(self, name, age, score):\n self.name = name\n self.age = age\n self.score = score\n\n# 读取文件中的内容\nwith open("students.txt", "r") as file:\n content = file.read()\n\n# 将文件中的内容转换成 Student 对象\nlines = content.split("\n") # 按换行符分割每一行\nstudents = []\nfor line in lines:\n if line:\n name, age, score = line.split("-") # 按"-"分割每个字段\n student = Student(name, int(age), int(score))\n students.append(student)\n\n# 求出学生总分数\ntotal_score = 0\nfor student in students:\n total_score += student.score\n\nprint("学生总分数为:", total_score)\n\n\n在这个解决方案中,首先定义了一个Student类来表示学生对象,包含姓名、年龄和分数属性。然后使用open函数打开文件,读取文件内容并保存到content变量中。接着使用split函数按换行符分割每一行,得到一个包含每行内容的列表lines。然后遍历lines列表,对每一行使用split函数按"-"分割成姓名、年龄和分数,然后创建一个Student对象并添加到students列表中。最后,遍历students列表,累加每个学生的分数,得到学生总分数并打印输出。
原文地址: https://www.cveoy.top/t/topic/p7r3 著作权归作者所有。请勿转载和采集!