确认尾随零的模式后,我们可以使用基于数组和 NumPy 工具的方法,像这样 -
len(test)-np.equal(test,0)[::-1].argmin()
如果您在该索引之前需要全零索引 -
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])
为了解释索引获取部分,让我们将其分解为步骤 -
# 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