gpt4 book ai didi

python - 根据多个条件对字典中的值求和

转载 作者:行者123 更新时间:2023-12-01 04:44:42 28 4
gpt4 key购买 nike

我正在尝试对多个字典之间的值求和,例如:

oneDic = {'A': 3, 'B': 0, 'C':1, 'D': 1, 'E': 2}
otherDic = {'A': 9, 'D': 1, 'E': 15}

我想对 oneDic 中的值求和如果otherDic 中找到它们并且如果 otherDic 中的对应值小于特定值

oneDic = {'A': 3, 'B': 0, 'C':1, 'D': 1, 'E': 2}
otherDic = {'A': 9, 'D': 1, 'E': 15}
value = 12
test = sum(oneDic[value] for key, value in oneDic.items() if count in otherTest[count] < value
return (test)

我期望值​​为 4,因为在 otherDic 中找不到 C,并且在 otherDic< 中找不到 E 的值 不小于

但是当我运行这段代码时,我遇到了一个可爱的关键错误,有人能给我指出正确的方向吗?

最佳答案

这个怎么样

sum(v for k, v in oneDic.items() if otherDic.get(k, value) < value)

这里我们迭代 k, v oneDic 对,仅当从 otherDic.get(k, value) 返回时才包​​含它们是 < valuedict.get有两个参数,第二个参数是可选的。如果未找到该键,则使用默认值。这里我们设置默认值为value这样就缺少 otherDic 中的键不包括在内。

顺便说一句,你得到 KeyError 的原因是因为您正在尝试访问 B and C在迭代中的某个时刻执行 otherDic['B']otherDic['C']那是 KeyError 。但是,使用 .getotherDic.get('B')将返回默认值 None因为您没有提供默认值 - 但它不会有 KeyError

关于python - 根据多个条件对字典中的值求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29760685/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com