Python实现:从TXT文件计算学生加权平均分并生成字典
解决方案
1. 定义科目分数权重
先明确每个科目内各分数的对应权重(按分数顺序匹配):
subject_weights = { 'Math': [0.05, 0.10, 0.15, 0.70], 'Physics': [0.05, 0.10, 0.15, 0.70], 'Chemistry': [0.05, 0.10, 0.15, 0.70], 'Biology': [0.05, 0.10, 0.15, 0.70], 'Literature': [0.05, 0.10, 0.10, 0.15, 0.60], 'Language': [0.05, 0.10, 0.10, 0.15, 0.60], 'History': [0.05, 0.10, 0.10, 0.15, 0.60], 'Geography': [0.05, 0.10, 0.10, 0.15, 0.60] }
2. 读取文件并计算加权平均分
编写函数处理TXT文件,逐行解析学生数据并计算各科加权平均分:
def calculate_weighted_averages(file_path): result = {} # 科目顺序与权重字典对应 subjects = ['Math', 'Physics', 'Chemistry', 'Biology', 'Literature', 'Language', 'History', 'Geography'] with open(file_path, 'r', encoding='utf-8') as f: next(f) # 跳过表头行 for line in f: line = line.strip() if not line: continue # 分割每行数据并去除多余空格 parts = [p.strip() for p in line.split(';')] student_id = parts[0] student_scores = {} for idx, subject in enumerate(subjects): # 将分数字符串转为整数列表 scores = list(map(int, parts[idx+1].split(','))) # 计算加权平均分并保留两位小数 weighted_avg = sum(score * weight for score, weight in zip(scores, subject_weights[subject])) student_scores[subject] = round(weighted_avg, 2) result[f'Student {student_id}'] = student_scores return result
3. 调用函数并输出结果
替换为你的TXT文件路径后运行:
file_path = 'students_scores.txt' final_result = calculate_weighted_averages(file_path) print(final_result)
输出示例
运行后会生成符合要求的字典格式,示例片段:
{ 'Student 1': {'Math': 7.6, 'Physics': 5.85, 'Chemistry': 7.15, 'Biology': 6.15, 'Literature': 7.7, 'Language': 6.8, 'History': 7.75, 'Geography': 6.9}, 'Student 2': {'Math': 6.7, 'Physics': 4.85, 'Chemistry': 7.7, 'Biology': 4.15, 'Literature': 5.7, 'Language': 6.85, 'History': 7.15, 'Geography': 5.1} }
内容的提问来源于stack exchange,提问作者Marcus
相关产品推荐
相关产品推荐

