首页 > 解决方案 > 在python中迭代二维数组中的填充区域

问题描述

假设我在 Python 中有一个二维数组,并添加了一些填充。我怎样才能只遍历新的填充区域?

例如

1 2 3
4 5 6
7 8 9

变成

x x x x x x x
x x x x x x x
x x 1 2 3 x x
x x 4 5 6 x x
x x 7 8 9 x x
x x x x x x x
x x x x x x x

我怎样才能只遍历x?

标签: pythonloopspadding

解决方案


不确定我是否理解您要执行的操作,但是如果您使用的是 numpy,则可以使用掩码:

import numpy as np

arr = np.array(np.arange(1,10)).reshape(3,3)

# mask full of True's
mask = np.ones((7,7),dtype=bool)
# setting the interior of the mask as False
mask[2:-2,2:-2] = False
# using zero padding as example
pad_arr = np.zeros((7,7))
pad_arr[2:-2,2:-2] = arr

print(pad_arr)

# loop for elements of the padding, where mask == True
for value in pad_arr[mask]:
    print(value)

回报:

[[0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 1. 2. 3. 0. 0.]
 [0. 0. 4. 5. 6. 0. 0.]
 [0. 0. 7. 8. 9. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0.]]

0.040 次(填充值)


推荐阅读