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
确认了尾随零的模式后,我们可以使用基于数组和NumPy工具的方法,就像这样-
如果你需要所有的零索引直到那个索引-
为了解释索引获取部分,我们将其分解为以下步骤-
你可以做到:
这是一个纯python几乎一行程序的解决方案,没有调用方法、构建堆栈、创建列表和其他低效之处:
然后您只需检索您的整数索引值
相关问题 更多 >
编程相关推荐