第7关:根据输入的字符串计算各科总分和平均分
时间: 2023-11-27 09:54:04 浏览: 37
好的,这个任务可以通过编写一个函数来完成。函数可以接收一个字符串作为输入,字符串中包含了学生的姓名和各科成绩,我们需要从中提取出各科成绩并计算总分和平均分。下面是一个示例函数的代码实现:
```python
def calculate_scores(input_string):
# 将字符串按换行符分割成多行
lines = input_string.split('\n')
# 获取第一行作为表头
headers = lines[0].split()
# 初始化各科总分和各科成绩数量
total_scores = {header: 0 for header in headers[1:]}
num_scores = {header: 0 for header in headers[1:]}
# 遍历每个学生的成绩
for line in lines[1:]:
# 将每个学生的成绩按空格分割成多个字段
fields = line.split()
# 获取学生姓名和各科成绩
name = fields[0]
scores = {header: int(score) for header, score in zip(headers[1:], fields[1:])}
# 更新各科总分和各科成绩数量
for header, score in scores.items():
total_scores[header] += score
num_scores[header] += 1
# 计算各科平均分
avg_scores = {header: total_scores[header] / num_scores[header] for header in headers[1:]}
# 返回各科总分和平均分
return total_scores, avg_scores
```
这个函数首先将输入字符串按换行符分割成多行,然后获取第一行作为表头,初始化各科总分和各科成绩数量,遍历每个学生的成绩,将每个学生的成绩按空格分割成多个字段,获取学生姓名和各科成绩,更新各科总分和各科成绩数量,最后计算各科平均分并返回各科总分和平均分。