擅长:python、mysql、java
<p>确认了尾随零的模式后,我们可以使用基于数组和NumPy工具的方法,就像这样-</p>
<pre><code>len(test)-np.equal(test,0)[::-1].argmin()
</code></pre>
<p>如果你需要所有的零索引直到那个索引-</p>
<pre><code>In [100]: mask = np.equal(test,0)
In [101]: idx = len(test)-mask[::-1].argmin()
In [102]: np.flatnonzero(mask[:idx])
Out[102]: array([5, 6, 7])
</code></pre>
<p>为了解释索引获取部分,我们将其分解为以下步骤-</p>
<pre><code># Mask of zeros
In [100]: mask = np.equal(test,0)
In [101]: mask
Out[103]:
array([False, False, False, False, False, True, True, True, False,
True, True, True])
# Flip it
In [104]: mask[::-1]
Out[104]:
array([ True, True, True, False, True, True, True, False, False,
False, False, False])
# Get the first index of False ones, which would be the last non-zero
# value from original array. Note that this is on flipped version of input
In [105]: mask[::-1].argmin()
Out[105]: 3
# Get the original index position by subtracting from the length of it
In [106]: len(test)-mask[::-1].argmin()
Out[106]: 9
</code></pre>