python 多维数组遍历_迭代和Python中的多维数组选择特定阵列

该博客介绍了如何在Python中对3D数组(如numpy数组)进行特定轴向的求和。通过使用`map`函数或列表推导式,可以有效地遍历并累加3D数组的指定子数组。示例中展示了沿着每个2x4矩阵的列进行求和的方法,给出了一种解决此类问题的解决方案。
摘要由CSDN通过智能技术生成

Imagine I have something like this:

import numpy as np

arra = np.arange(16).reshape(2, 2, 4)

which gives

array([[[0, 1, 2, 3],

[4, 5, 6, 7]],

[[8, 9, 10, 11],

[12, 13, 14, 15]]])

and I want to make a loop that runs along specific subarrays (in this case, I want to run along each 'column' of each 'matrix') and sum the result (that is, selecting 0 and 4 and summing them (4), selecting 1 and 5 and summing them (6), ..., selecting 3 and 7 and summing them (10), selecting 8 and 12 and summing them (20), ..., selecting 11 and 15 and summing them (26)).

I had thought doing that with the apparently natural:

for i in arra[i, j, k]:

for j in arra[i, j, k]:

for k in arra[i, j, k]:

sum...

The problem is that Python certainly doesn't allow to do what I want in this way. If it were a 2D array it would be easier as I know that the iterator first runs through the rows, so you can transpose to run along the columns, but for a multidimensional (3D in this case) array (N, M, P) with N, M, P >> 1, I was wondering how it could be done.

解决方案

You can use map to get this done:

import numpy as np

arra = np.arange(16).reshape(2, 2, 4)

Then the command:

map(sum, arra)

gives you the desired output:

[array([ 4, 6, 8, 10]), array([20, 22, 24, 26])]

Alternatively, you can also use a list comprehension:

res = [sum(ai) for ai in arra]

Then res looks like this:

[array([ 4, 6, 8, 10]), array([20, 22, 24, 26])]

EDIT:

If you want to add identical rows - as you mentioned in the comments below this answer - you can do (using zip):

map(sum, zip(*arra))

which gives you the desired output:

[array([ 8, 10, 12, 14]), array([16, 18, 20, 22])]

For the sake of completeness also the list comprehension:

[sum(ai) for ai in zip(*arra)]

which gives you the same output.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值