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

xzabzqsa  于 2023-01-20  发布在  Python
关注(0)|答案(5)|浏览(152)

我想从下面的列表中总结一下

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]]]

我想做的是如下的总结

[1,1,1]+[1,1,1]+[1,1,1]  = 9
   [2,2,2]+[2,2,2]+[2,2,2]  = 18
       ....                 = 27
                            = 36
                            = 45

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

[9,18,27,36,45]
uz75evzq

uz75evzq1#

您可以使用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]
9rygscc1

9rygscc12#

import numpy as np
lis=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]]])
print(lis.sum(axis=0).sum(axis=1))
easiest I think with numpy.
output

[ 9 18 27 36 45]

li9yvcax

li9yvcax3#

使用zip()
代码:

import numpy as np
lis=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=[]

for i in zip(*lis):
    res.append(sum(sum(i)))
print(res)

输出:

[9, 18, 27, 36, 45]
    • 列出理解**:
print([sum(sum(i)) for i in zip(*lis)]) #Same output.
raogr8fs

raogr8fs4#

这真的不是“Python般”的解决方案,但我相信它会很适合你。

import numpy as np

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]]])

s = [0 for i in range(len(A[0]))]

for element in A:
    for i, ar in enumerate(element):
        s[i] += sum(ar)

print(s)
nhhxz33t

nhhxz33t5#

a = [[[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]]]

result = [sum(x)+sum(y)+sum(z) for x,y,z in zip(a[0], a[1], a[1])]

相关问题