【问题标题】:Summing values in a dictionary based on multiple conditions根据多个条件对字典中的值求和
【发布时间】:2015-04-21 00:16:50
【问题描述】:

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

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

我想总结oneDic中的值if它们在otherDic中找到如果otherDic中对应的值小于a具体值

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 的值不小于 value

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

【问题讨论】:

    标签: python dictionary sum iteration multiple-conditions


    【解决方案1】:

    这个怎么样

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

    这里我们迭代 k, v 对 oneDic 并且仅当来自 otherDic.get(k, value) 的返回为 &lt; value 时才包含它们。 dict.get 有两个参数,第二个是可选的。如果未找到密钥,则使用默认值。这里我们将默认值设置为value,这样otherDic 中缺少的键就不会被包括在内。

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

    【讨论】:

      【解决方案2】:

      以下代码 sn-p 有效。我不知道你代码中的count 变量是什么:

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

      Link to working code

      【讨论】:

      • 我比另一个答案更喜欢这个,因为这两个条件都经过了显式测试。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-27
      • 2020-03-05
      • 1970-01-01
      • 1970-01-01
      • 2021-10-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多