擅长:python、mysql、java
<p>以非矢量化方式:</p>
<pre><code>>>> x = [1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0]
>>> c, y = 0, []
>>> for i in x:
... if i == 1:
... y.append(c)
... else:
... c += 1
...
>>> y
[0, 0, 1, 2, 2, 5]
</code></pre>
<hr/>
<p>有关矢量化解决方案,请参见@Divakar的答案:</p>
<p>在<code>numpy</code>中,首先用<a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.nonzero.html" rel="nofollow noreferrer">^{<cd2>}</a>找到非零索引:</p>
^{pr2}$
<p>然后用索引长度的范围数组减去:</p>
<pre><code>>>> idx = np.nonzero(x)[0]
>>> np.arange(len(idx))
array([0, 1, 2, 3, 4, 5])
>>> np.nonzero(x)[0] - np.arange(len(idx))
array([0, 0, 1, 2, 2, 5])
>>> np.arange(x.count(1))
array([0, 1, 2, 3, 4, 5])
>>> np.nonzero(x)[0] - np.arange(x.count(1))
array([0, 0, 1, 2, 2, 5])
</code></pre>