There is a midterm.csv file about the grading result of a course's midterm exam. The first row presents the header. Then, each row presents a student's enrolled name and his or her score. Write a program to read the file and collect all the scores in a list (without header row!) Download the midterm.csv file. Classify those scores according to the criteria given by question 2 in Problem Set 1. Then, draw a histogram with plotly for ranks A, B, C, D, F
时间: 2024-02-22 22:58:41 浏览: 82
Sure! For reading and processing the CSV file, we can use the `csv` module in Python. Here's the code to read and collect all the scores in a list:
```python
import csv
scores = []
with open('midterm.csv', newline='') as csvfile:
reader = csv.reader(csvfile)
next(reader) # skip header row
for row in reader:
scores.append(int(row[1]))
print(scores)
```
This code will create a list `scores` containing all the numeric scores from the CSV file.
For the second part of the question, we need to classify the scores into A, B, C, D, and F categories. According to the criteria given in Problem Set 1, we can use the following classification:
- A: score >= 90
- B: 80 <= score < 90
- C: 70 <= score < 80
- D: 60 <= score < 70
- F: score < 60
Here's the code to classify the scores and count the number of scores in each category:
```python
counts = {'A': 0, 'B': 0, 'C': 0, 'D': 0, 'F': 0}
for score in scores:
if score >= 90:
counts['A'] += 1
elif score >= 80:
counts['B'] += 1
elif score >= 70:
counts['C'] += 1
elif score >= 60:
counts['D'] += 1
else:
counts['F'] += 1
print(counts)
```
This code will create a dictionary `counts` containing the number of scores in each category.
Finally, we can use the `plotly` library to create a histogram of the scores. Here's the complete code:
```python
import csv
import plotly.graph_objs as go
scores = []
with open('midterm.csv', newline='') as csvfile:
reader = csv.reader(csvfile)
next(reader) # skip header row
for row in reader:
scores.append(int(row[1]))
counts = {'A': 0, 'B': 0, 'C': 0, 'D': 0, 'F': 0}
for score in scores:
if score >= 90:
counts['A'] += 1
elif score >= 80:
counts['B'] += 1
elif score >= 70:
counts['C'] += 1
elif score >= 60:
counts['D'] += 1
else:
counts['F'] += 1
labels = ['A', 'B', 'C', 'D', 'F']
values = [counts[label] for label in labels]
fig = go.Figure([go.Bar(x=labels, y=values)])
fig.show()
```
This code will create a histogram of the scores, showing the number of scores in each category.
阅读全文