<p>这里有一个想法,很容易实现,应该执行得相当快。你知道吗</p>
<p>我将使用0和1,这样看起来更清晰一些。你知道吗</p>
<p>以下是起始阵列:</p>
<pre><code>>>> a
array([[1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1],
[1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1],
[1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1],
[1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1],
[1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1]])
</code></pre>
<p>使用<code>np.logical_and.accumulate</code>从左到右累加,从左到右翻转,再次执行相同操作,向后翻转,然后将两个数组中的“或”组合在一起:</p>
<pre><code>>>> andacc = np.logical_and.accumulate
>>> (andacc(a, axis=1) | andacc(a[:, ::-1], axis=1)[:, ::-1]).astype(int)
array([[1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1],
[1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1],
[1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1],
[1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1],
[1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1]])
</code></pre>
<p>(省略<code>.astype(int)</code>以保留布尔数组,而不是0和1。)</p>
<p>这是一个三角形:</p>
<pre><code>>>> b
array([[1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 1],
[1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1],
[1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1],
[0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0]])
>>> (andacc(b, axis=1) | andacc(b[:, ::-1], axis=1)[:, ::-1]).astype(int)
array([[1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1],
[1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])
</code></pre>