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

Python中如何按科目计算通过测试的总分占比?

问题描述

我有包含4个属性的列表:subject、test、score和result。已经实现计算每个科目的总分(该科目所有测试分数相加),现在需要计算每个科目中通过测试的总分与该科目所有测试总分的比值。

已运行正常的代码第一部分:

from collections import defaultdict

d = defaultdict(float)
dc = defaultdict(float) 

subject = ['Math', 'Math', 'Math', 'Math', 'Biology', 'Biology', 'Chemistry']
test = ['Test 1','Test 2','Test 3','Test 4','Test 1','Test 2','Test 1']
score = ['1.0', '0.0', '4.0', '0.0', '4.0', '6.0', '2.0']
result = ['fail', 'fail', 'pass', 'fail', 'fail', 'pass', 'pass']

points = [float(x) for x in score]

mylist = list(zip(subject, test, points, result))

for subject, test, points, completion in mylist:
    d[subject] += points
    dc[(subject, test)] += points
print(d)

这段代码的输出符合预期:

{'Math': 5.0, 'Biology': 10.0, 'Chemistry': 2.0}

当前剩余代码的输出不符合需求:

dc = {f"{subject} {test}" : round(points / d[subject], 2)
       if d[subject]!=0 else 'division by zero'  
       for (subject, test), points in dc.items()}
      
print(dc)

实际输出:

{'Math Test 1': 0.2, 'Math Test 2': 0.0, 'Math Test 3': 0.8, 'Math Test 4': 0.0, 'Biology Test 1': 0.4, 'Biology Test 2': 0.6, 'Chemistry Test 1': 1.0}

预期输出:

Math: 4/5, Biology: 6/10, Chemistry: 2/2

解决方案

要实现需求,需新增字典统计每个科目通过测试的总分,再结合科目总分计算比值。修改后的完整代码如下:

from collections import defaultdict

d = defaultdict(float)
passed_total = defaultdict(float) 

subject = ['Math', 'Math', 'Math', 'Math', 'Biology', 'Biology', 'Chemistry']
test = ['Test 1','Test 2','Test 3','Test 4','Test 1','Test 2','Test 1']
score = ['1.0', '0.0', '4.0', '0.0', '4.0', '6.0', '2.0']
result = ['fail', 'fail', 'pass', 'fail', 'fail', 'pass', 'pass']

points = [float(x) for x in score]
mylist = list(zip(subject, test, points, result))

# 统计科目总分和通过测试的总分
for subj, _, point, res in mylist:
    d[subj] += point
    if res == "pass":
        passed_total[subj] += point

# 生成预期格式的结果
result_dict = {}
for subj in d:
    total = d[subj]
    passed = passed_total.get(subj, 0.0)
    if total == 0:
        result_dict[subj] = 'division by zero'
    else:
        # 格式化为整数分数形式(若为整数则去掉小数部分)
        numerator = int(passed) if passed.is_integer() else passed
        denominator = int(total) if total.is_integer() else total
        result_dict[subj] = f"{numerator}/{denominator}"

print(result_dict)

输出结果

运行代码后输出与预期一致:

{'Math': '4/5', 'Biology': '6/10', 'Chemistry': '2/2'}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 12:25:21