程序功能:统计学生Python课程成绩 读取CSV文件(文本格式)student_score.csv中所有的行,每行包含了学生学号,姓名及Python成绩(有列名),如下: 学号,姓名,Python 202203,张三,90 202209,李四,88 202218,王五,79 ……,……,…… 计算所有学生Python成绩的平均分和中位数,把统计结果写入文本文件result.txt中。
时间: 2024-03-01 22:52:33 浏览: 24
好的,可以为您提供Python代码实现该功能。请确保在运行代码之前,已将student_score.csv文件放置在代码所在目录。
```python
import csv
import statistics
# 读取CSV文件
with open('student_score.csv', 'r', encoding='utf-8') as f:
reader = csv.DictReader(f)
scores = []
for row in reader:
score = int(row['Python'])
scores.append(score)
# 计算平均分和中位数
avg_score = sum(scores) / len(scores)
median_score = statistics.median(scores)
# 写入结果到文件
with open('result.txt', 'w', encoding='utf-8') as f:
f.write('Python课程成绩统计结果:\n\n')
f.write('平均分:{:.2f}\n'.format(avg_score))
f.write('中位数:{}\n'.format(median_score))
```
代码解释:
1. 使用csv模块的DictReader函数读取CSV文件,每行数据变成一个字典,方便取出Python成绩列的数据。
2. 将所有Python成绩存储在列表scores中。
3. 使用statistics模块的median函数计算中位数,使用sum函数和len函数计算平均分。
4. 使用打开文件方式为写入模式的with语句,打开result.txt文件,将结果写入文件中。其中,使用.format()方法将平均分和中位数插入到字符串中。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)