使用Python读取成绩文件计算各类平均分及学期总分
Python Solution to Calculate Grade Averages from a Score File
Hey Scarlett, let's solve this grade calculation problem together! I'll walk you through a complete implementation that reads the score file, maps grades to their categories, computes all required averages, and outputs results in your preferred format.
Step-by-Step Implementation
Here's a robust script that handles variable column positions for hw, project, and quiz scores:
import csv def calculate_grades(file_path): with open(file_path, mode='r') as file: reader = csv.reader(file) # Read the header row to get category labels header = next(reader) # Iterate over each student's row for row in reader: if not row: # Skip empty rows continue # Extract student name using header positions last_name = row[header.index('last')] first_name = row[header.index('first')] # Collect scores by their category hw_scores = [] quiz_scores = [] project_scores = [] for col_idx, category in enumerate(header): score_str = row[col_idx].strip() if not score_str: continue # Skip empty score entries score = float(score_str) if category == 'hw': hw_scores.append(score) elif category == 'quiz': quiz_scores.append(score) elif category == 'project': project_scores.append(score) # Calculate category averages (avoid division by zero) hw_avg = sum(hw_scores) / len(hw_scores) if hw_scores else 0.0 quiz_avg = sum(quiz_scores) / len(quiz_scores) if quiz_scores else 0.0 project_avg = sum(project_scores) / len(project_scores) if project_scores else 0.0 # Compute semester average using the weighted formula sem_avg = (hw_avg * 0.2) + (quiz_avg * 0.2) + (project_avg * 0.6) # Print results in your desired format print(f"{last_name}, {first_name}: hw avg = {hw_avg:.2f}, quiz avg = {quiz_avg:.2f}, proj avg = {project_avg:.2f}, sem avg = {sem_avg:.2f}") # Example usage: replace 'scores.csv' with your actual file path calculate_grades('scores.csv')
Key Features Explained
- Dynamic Header Mapping: Uses
header.index()to locate columns regardless of their order, so the script works even if the header sequence changes. - Safe Score Handling: Skips empty entries and checks for non-empty score lists before calculating averages to avoid division-by-zero errors.
- Formatted Output: Uses f-strings to match your requested output style, rounding all averages to 2 decimal places for readability.
Example Test Case
If your scores.csv looks like this:
last, first, hw, hw, project, quiz, hw, project Cat, Figaro, 70, 75, 80, 95, 69, 79 Doe, John, 85, 90, 92, 88, 87, 91
The script will output:
Cat, Figaro: hw avg = 71.33, quiz avg = 95.00, proj avg = 79.50, sem avg = 81.07 Doe, John: hw avg = 87.33, quiz avg = 88.00, proj avg = 91.50, sem avg = 90.27
Quick Adjustments
- If your file uses a different delimiter (like tabs), add
delimiter='\t'to thecsv.reader()call. - If you need to handle non-numeric entries (like 'N/A' for missing scores), you can add a try-except block around the
float(score_str)line to skip invalid values.
内容的提问来源于stack exchange,提问作者idontcare




