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

Python中基于字典键匹配条件对对应值求和的实现问题

错误原因

原代码中if dic.keys() > threshold的逻辑不成立,dic.keys()返回的是字典所有键的集合,不能直接和单个数值做比较,也没有实现对每个键逐一判断是否符合阈值要求的逻辑。

正确实现代码
# 定义字典、阈值、除数
dic = {1: 45, 2: 4, 3: 56, 4: 667, 5: 90}
threshold = 3
num_to_be_divided = 100

# 筛选键>=阈值的对应值求和
sum_val = sum(v for k, v in dic.items() if k >= threshold)
# 计算最终结果
prob = sum_val / num_to_be_divided
结果说明

符合阈值要求的键为3、4、5,对应值求和结果为56 + 667 + 90 = 813,除以100后得到的prob值为8.13。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 07:09:02