You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在不使用pandas/numpy的情况下计算二维列表中考试分数的百分比与平均分

考试分数百分比输出问题

我有一份考试分数的CSV数据,现有程序已将数据读取为包含满分行的二维列表,且实现了移除满分行的函数来展示学生分数,但现在需要编写函数,让每个学生的分数以百分比形式单独显示在一行,同时输出平均分百分比。


现有代码

def getData():
    with open("testscores.csv","r") as file:
        lineArray = file.read().splitlines()
        matrix = []
        for line in lineArray:
            matrix.append(line.split(","))
    return matrix

def fullScores(matrix):
    matrix.pop(0)
    return matrix

def printscores(matrix):
    for counter in matrix:
        for values in counter:
            print(values, end= " ")
        print()

matrix = getData()
matrix = fullScores(matrix)
print()
printscores(matrix)

当前输出

Bob 10 9 7 8 10 9 9 9 10 8 8 10 9 9 
Sue 8 8 8 9 4 8 9 7 8 3 10 10 7 9
Jan 6 6 0 5 7 9 4 7 8 5 7 1 5 9
Sam 8 8 8 7 7 7 9 9 9 9 8 9 10 8
Tom 9 9 9 9 9 9 9 9 9 10 9 9 9 9

期望输出

Bob 100% 90% 70% 80% 100% 90% 90% 90% 100% 80% 80% 100% 90% 90% Average = 89%
Sue 80% 80% 80% 90% 40% 80% 90% 70% 80% 30% 100% 100% 70% 90% Average = 77%
...

CSV数据

Testoutof,10,11,12,11,10,11,9,10,10,11,10,12,10,9
Bob,10,9,7,8,10,9,9,9,10,8,8,10,9,9
Sue,8,8,8,9,4,8,9,7,8,3,10,10,7,9
Jan,6,6,0,5,7,9,4,7,8,5,7,1,5,9
Sam,8,8,8,7,7,7,9,9,9,9,8,9,10,8
Tom,9,9,9,9,9,9,9,9,9,10,9,9,9,9

解决方案

核心问题是原代码直接丢弃了满分行,导致无法计算百分比。修改思路:保留满分行数据,逐个计算单题百分比,再计算加权平均分百分比。

修改后的代码

def getData():
    with open("testscores.csv","r") as file:
        lineArray = file.read().splitlines()
        matrix = []
        for line in lineArray:
            matrix.append(line.split(","))
    return matrix

def process_scores(matrix):
    # 提取满分数据并转换为整数
    max_scores = list(map(int, matrix[0][1:]))
    # 获取所有学生行
    student_rows = matrix[1:]
    processed_lines = []
    
    for row in student_rows:
        name = row[0]
        scores = list(map(int, row[1:]))
        percentages = []
        total_score = 0
        total_max = 0
        
        # 计算每道题的百分比,并累加总分与总满分
        for score, max_score in zip(scores, max_scores):
            percent = round((score / max_score) * 100)
            percentages.append(f"{percent}%")
            total_score += score
            total_max += max_score
        
        # 计算平均分百分比
        avg_percent = round((total_score / total_max) * 100)
        # 拼接成目标格式的行
        processed_line = f"{name} {' '.join(percentages)} Average = {avg_percent}%"
        processed_lines.append(processed_line)
    
    return processed_lines

def printscores(scores_list):
    for line in scores_list:
        print(line)

matrix = getData()
processed_scores = process_scores(matrix)
print()
printscores(processed_scores)

代码说明

  1. 保留满分行:不再直接删除首行,而是提取首行的满分数据用于百分比计算
  2. 单题百分比计算:通过zip配对学生得分与对应题目的满分,计算后格式化为带%的字符串
  3. 加权平均分:用学生总分除以所有题目的总满分,得到更准确的平均百分比
  4. 格式拼接:将学生姓名、所有题目的百分比、平均分拼接成符合要求的一行文本

内容的提问来源于stack exchange,提问作者Mateo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 04:50:47