<p><strong>方法1</strong></p>
<p>这里有一种方法使用<a href="https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#basic-slicing-and-indexing" rel="nofollow noreferrer">^{<cd1>}</a>和<a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.ufunc.accumulate.html" rel="nofollow noreferrer">^{<cd2>}</a>来检测岛的启动和停止索引-</p>
<pre><code>def fill_inner_islands(a):
acc = np.maximum.accumulate
start = a.argmax()
end = a.size-a[::-1].argmax()
a0 = ~a[start:end]
a[start:end] = ~(acc(a0) & acc(a0[::-1])[::-1])
</code></pre>
<p>样本运行-</p>
<p>案例1:</p>
^{pr2}$
<p>案例2:</p>
<pre><code>In [144]: a.astype(int)
Out[144]: array([1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0])
In [145]: fill_inner_islands(a)
In [146]: a.astype(int)
Out[146]: array([1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0])
</code></pre>
<p>案例三:</p>
<pre><code>In [148]: a.astype(int)
Out[148]: array([1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0])
In [149]: fill_inner_islands(a)
In [150]: a.astype(int)
Out[150]: array([1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0])
</code></pre>
<p><strong>方法2</strong></p>
<p>更简单的方法-</p>
<pre><code>def fill_inner_islands_v2(a):
# Get stop and end indices of leading and trailing islands.
# We do this by using one-off shifted slices and looking for the fall
# in forward direction and fall in flipped direction
start = (a[1:] < a[:-1]).argmax()+1
end = a.size - 1 - (a[:-1][::-1] < a[1:][::-1]).argmax()
# Get the slice within those indices and assign as all False
if ~a[start:end].all(): # To handle all True in input array
a[start:end] = 0
</code></pre>