请根据以下描述完成操作。小明-18-88;小红-17-90;1 读取文件中的内容2 将文件中的内容转换成Student对象姓名-年龄-分数3 求出学生总分数
以下是一个可能的解决方案:
# 定义Student类
class Student:
def __init__(self, name, age, score):
self.name = name
self.age = age
self.score = score
# 读取文件中的内容
with open("students.txt", "r") as file:
content = file.read()
# 将文件中的内容转换成Student对象
lines = content.split("\n") # 按换行符分割每一行
students = []
for line in lines:
if line:
name, age, score = line.split("-") # 按"-"分割每个字段
student = Student(name, int(age), int(score))
students.append(student)
# 求出学生总分数
total_score = 0
for student in students:
total_score += student.score
print("学生总分数为:", total_score)
在这个解决方案中,首先定义了一个Student类来表示学生对象,包含姓名、年龄和分数属性。然后使用open函数打开文件,读取文件内容并保存到content变量中。接着使用split函数按换行符分割每一行,得到一个包含每行内容的列表lines。然后遍历lines列表,对每一行使用split函数按"-"分割成姓名、年龄和分数,然后创建一个Student对象并添加到students列表中。最后,遍历students列表,累加每个学生的分数,得到学生总分数并打印输出
原文地址: https://www.cveoy.top/t/topic/ipG2 著作权归作者所有。请勿转载和采集!