用python读取各科成绩文件(scores.csv),完成以下需求:(1) 输出各科前 10条数据(2)输出各科成绩的最高分(3)输出各科成绩的最低分(4) 输出各科成绩的平均分(5) 添加一列数据,列名为status。其值为“正常”,输出前5条数据
时间: 2024-03-05 20:52:55 浏览: 76
好的,我来解答你的问题。
可以使用Python内置的csv模块来读取csv文件。
以下是代码示例:
```python
import csv
# 读取csv文件
with open('scores.csv', 'r', encoding='utf-8') as f:
reader = csv.reader(f)
# 读取表头
header = next(reader)
# 将数据按照科目分组
subjects = {}
for row in reader:
subject = row[0]
if subject not in subjects:
subjects[subject] = []
subjects[subject].append(row)
# 输出各科前10条数据
for subject in subjects:
print(subject + '前10条数据:')
for row in subjects[subject][:10]:
print(row)
# 输出各科成绩的最高分
for subject in subjects:
scores = [float(row[1]) for row in subjects[subject]]
max_score = max(scores)
print(subject + '的最高分:' + str(max_score))
# 输出各科成绩的最低分
for subject in subjects:
scores = [float(row[1]) for row in subjects[subject]]
min_score = min(scores)
print(subject + '的最低分:' + str(min_score))
# 输出各科成绩的平均分
for subject in subjects:
scores = [float(row[1]) for row in subjects[subject]]
avg_score = sum(scores) / len(scores)
print(subject + '的平均分:' + str(avg_score))
# 添加一列数据,列名为status。其值为“正常”
for subject in subjects:
for row in subjects[subject][:5]:
row.append('正常')
print(row)
```
希望能解决你的问题。
阅读全文