【问题标题】:Iterate over padded area in 2D array in python在python中迭代二维数组中的填充区域
【发布时间】:2021-05-10 18:59:07
【问题描述】:

假设我在 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?

【问题讨论】:

    标签: python loops padding


    【解决方案1】:

    不确定我是否理解你想要做什么,但如果你使用的是 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.0 40 次(填充值)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-28
      • 2015-04-04
      • 2012-11-05
      • 1970-01-01
      相关资源
      最近更新 更多