如何在Python中对列表列表中的第二个列表求和

foy*_*foy 1 python arrays numpy python-3.x

我想从下面的列表中求和

array([[[1, 1, 1],
      [2, 2, 2],
      [3, 3, 3],
      [4, 4, 4],
      [5, 5, 5]],

     [[1, 1, 1],
      [2, 2, 2],
      [3, 3, 3],
      [4, 4, 4],
      [5, 5, 5]],

     [[1, 1, 1],
     [2, 2, 2],
     [3, 3, 3],
     [4, 4, 4],
     [5, 5, 5]]]
Run Code Online (Sandbox Code Playgroud)

我想要的是总结如下

   [1,1,1]+[1,1,1]+[1,1,1]  = 9
   [2,2,2]+[2,2,2]+[2,2,2]  = 18
       ....                 = 27
                            = 36
                            = 45
Run Code Online (Sandbox Code Playgroud)

并返回如下列表作为最终列表:

[9,18,27,36,45]
Run Code Online (Sandbox Code Playgroud)

Man*_*ngh 5

您可以使用np.sum

a = np.array([[[1, 1, 1],
  [2, 2, 2],
  [3, 3, 3],
  [4, 4, 4],
  [5, 5, 5]],

 [[1, 1, 1],
  [2, 2, 2],
  [3, 3, 3],
  [4, 4, 4],
  [5, 5, 5]],

 [[1, 1, 1],
 [2, 2, 2],
 [3, 3, 3],
 [4, 4, 4],
 [5, 5, 5]]])

res = np.sum(a, axis=(0,2))
# Does reduction along axis 0 and 2 by doing summation.
# numpy takes tuple of axis indices to do reduction 
# simultaneously along those axis.
print(res.tolist())
>> [ 9, 18, 27, 36, 45]
Run Code Online (Sandbox Code Playgroud)