<p>多亏了<a href="https://gist.github.com/alimanfoo/c5977e87111abe8127453b21204c1065" rel="nofollow noreferrer">find_runs.py</a></p>
<p>另一个答案是:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
def find_runs(x):
"""Find runs of consecutive items in an array."""
# ensure array
x = np.asanyarray(x)
if x.ndim != 1:
raise ValueError('only 1D array supported')
n = x.shape[0]
# handle empty array
if n == 0:
return np.array([]), np.array([]), np.array([])
else:
# find run starts
loc_run_start = np.empty(n, dtype=bool)
loc_run_start[0] = True
np.not_equal(x[:-1], x[1:], out=loc_run_start[1:])
run_starts = np.nonzero(loc_run_start)[0]
# find run values
run_values = x[loc_run_start]
# find run lengths
run_lengths = np.diff(np.append(run_starts, n))
return run_values, run_starts, run_lengths
if __name__ == "__main__":
QbStates = np.array([
[0, 0, 1, 1, 0, 0],
[0, 0, 1, 1, 0, 0],
[1, 0, 1, 1, 0, 0],
[1, 1, 1, 1, 0, 1],
[0, 1, 0, 0, 1, 1],
[0, 1, 0, 0, 1, 1],
[1, 0, 1, 1, 0, 1]])
print('QbStates: \n{}'.format(QbStates))
lifes = np.array([], dtype=np.int64).reshape(0,QbStates.shape[0])
for row in QbStates.T:
values, positions, times = find_runs(row)
life = np.array([],dtype=np.int64)
for v, t in zip(values, times):
life = np.append(life, np.repeat(v*t,t))
lifes = np.vstack([lifes, life])
# Transpose to get the answer
print('LifeStates:\n {}'.format(lifes.T))
</code></pre>
<p>获得的结果</p>
<pre class="lang-py prettyprint-override"><code>QbStates:
[[0 0 1 1 0 0]
[0 0 1 1 0 0]
[1 0 1 1 0 0]
[1 1 1 1 0 1]
[0 1 0 0 1 1]
[0 1 0 0 1 1]
[1 0 1 1 0 1]]
LifeStates:
[[0 0 4 4 0 0]
[0 0 4 4 0 0]
[2 0 4 4 0 0]
[2 3 4 4 0 4]
[0 3 0 0 2 4]
[0 3 0 0 2 4]
[1 0 1 1 0 4]]
</code></pre>