获取嵌套列表字典中所有值的总和

时间:2018-07-15 04:33:48

标签: python python-3.x

Banking_Deposits = {'January':[15000,9800,10100],  'Feburary':[2500,1400,14100], 'March': [20000,78366]}

total_dep = sum(Banking_Deposits.values())

我想获得这三个月全部存款的总和。但是,我返回此错误:

TypeError: unsupported operand type(s) for +: 'int' and 'list'

3 个答案:

答案 0 :(得分:3)

目前sum()并没有遍历字典中的每个存款,而是遍历了Banking_Deposits.values()内部的每个列表。由于sum的初始值设定项为0(即int),因此在sum尝试将每个列表添加到0时会遇到错误。一种解决方案是先对列表进行展平,然后再取和:

sum(val for value in Banking_Deposits.values() for val in value)

答案 1 :(得分:3)

更直观的方法是进行嵌套总和:

sum(sum(x) for x in Banking_Deposits.values())

您还可以使用sum's start参数首先加入列表:

sum(sum(Banking_Deposits.values(), []))

start的默认值为0,这就是为什么出现错误:0 + [...]不计算的原因。更不用说您的原始总和会产生一个很长的列表而不是一个数字,因为那是您将列表加在一起后得到的。

链接列表的更好方法是使用itertools.chain.from_iterable,它不会将多个列表分配为副产品:

sum(chain.from_iterable(Banking_Deposits.values()))

@Primusa's answer建议使用一种等效且更直观的方法来展平我强烈建议的值。

答案 2 :(得分:2)

只需遍历字典,通过分配键来获取其值,然后对其求和。像这样:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <script src="https://aframe.io/releases/0.8.0/aframe.min.js"></script>
  </head>
  <body>
    <a-scene screenshot="width: 640; height: 320">
      <a-entity id="box" geometry="primitive: box; width: 1; depth: 1; height: 1" position="-1 0.5 -3" rotation="0 45 0" material="color: #4CC3D9"></a-entity>
      <a-entity id="sphere" geometry="primitive: sphere; radius: 1.25" material="color: #EF2D5E" position="0 1.25 -5"></a-entity>
      <a-entity id="cylinder" geometry="primitive: cylinder; radius: 0.5; height: 1.5" position="1 0.75 -3" material="color: #FFC65D"></a-entity>
      <a-entity id="plane" position="0 0 -4" rotation="-90 0 0" geometry="primitive: plane; width: 4; height: 4" material="color: #7BC8A4"></a-entity>
      <a-entity id="sky" geometry="primitive: sphere; radius: 100" material="color: #ECECEC; shader: flat; side: back"></a-entity>
    </a-scene>

    <script>
      document.querySelector('a-scene').components.screenshot.capture('perspective')
    </script>
  </body>
</html>
相关问题