多行列数字/单词出现统计:科目成绩达标人数与频次分析求助
Hey there! Let's tackle this problem step by step. Based on your file structure (each line follows student_name subject1 grade1 subject2 grade2 ...), here's a practical Python solution that covers all your requirements: counting students with grades >5 per subject, tallying grade frequencies, and finding the most common grade for each subject.
Step 1: Solution Code
from collections import defaultdict, Counter # Initialize a data structure to track each subject's metrics subject_stats = defaultdict(lambda: { "students_above_5": set(), # Use a set to avoid duplicate student counts "grade_frequencies": Counter() }) # Read and process the file (replace "grades.txt" with your actual file path) with open("grades.txt", "r") as file: for line in file: line_parts = line.strip().split() if not line_parts: continue # Skip empty lines student_name = line_parts[0] # Iterate over subject-grade pairs (start at index 1, step by 2) for idx in range(1, len(line_parts), 2): subject = line_parts[idx] grade = int(line_parts[idx + 1]) # Convert grade to integer # Update students with grades >5 if grade > 5: subject_stats[subject]["students_above_5"].add(student_name) # Update grade frequency count subject_stats[subject]["grade_frequencies"][grade] += 1 # Print the final statistics for each subject for subject, stats in subject_stats.items(): print(f"=== {subject} Statistics ===") # Count of students with grade >5 print(f"Students with grade >5: {len(stats['students_above_5'])}") # Grade occurrence counts print("Grade frequency breakdown:") for grade, count in sorted(stats["grade_frequencies"].items()): print(f" Grade {grade}: {count} occurrences") # Most common grade(s) (handle ties) most_common_grades = stats["grade_frequencies"].most_common() if most_common_grades: max_count = most_common_grades[0][1] top_grades = [str(g) for g, c in most_common_grades if c == max_count] print(f"Most common grade(s): {', '.join(top_grades)} (appeared {max_count} times)") print()
Step 2: Key Explanations
- Data Structure Choice: We use
defaultdictto automatically initialize metrics for new subjects, andCounterto effortlessly tally grade frequencies. Asetis used for students with grades >5 to ensure each student is counted only once per subject (even if there were duplicate entries in the file). - File Parsing: Each line is split into parts, then we loop through pairs of elements (subject followed by grade) starting from index 1.
- Handling Ties: The
most_common()method returns grades sorted by frequency. We check for ties by collecting all grades that match the highest frequency count.
Example Output
Using your sample input line:
Robert Java 8 Algorithms 8 Math 6 Andrew Java 9 Algorithms 7 Math 5
The code would output:
=== Java Statistics === Students with grade >5: 2 Grade frequency breakdown: Grade 8: 1 occurrences Grade 9: 1 occurrences Most common grade(s): 8, 9 (appeared 1 times) === Algorithms Statistics === Students with grade >5: 2 Grade frequency breakdown: Grade 7: 1 occurrences Grade 8: 1 occurrences Most common grade(s): 7, 8 (appeared 1 times) === Math Statistics === Students with grade >5: 1 Grade frequency breakdown: Grade 5: 1 occurrences Grade 6: 1 occurrences Most common grade(s): 5, 6 (appeared 1 times)
Quick Adjustments
- If your grades are decimals instead of integers, replace
int(line_parts[idx + 1])withfloat(line_parts[idx + 1]). - To save results to a file instead of printing, replace the
print()calls with file write operations.
内容的提问来源于stack exchange,提问作者Szabolcs-Ervin Szigeti
相关产品推荐
相关产品推荐

