与
a
作为输入数组/列表,我们可以-
# Compare against 1 to get a mask. Append on either sides with False
# so that when do consecutive comparison next, we will catch the
# transitions including leading and trailing islands that might be
# starting at the first element of the array or ending as the last one.
# These transitions are signal the start and end of each island of 1s.
m = np.r_[False,np.asarray(a)==1,False]
idx = np.flatnonzero(m[:-1]!=m[1:])
# After catching those start,end indices, simply subtract between start
# and end indices to get island lengths. That's our o/p.
out = idx[1::2]-idx[::2]
如果
一
已经是一个数组,我们也可以使用
a.astype(bool)
代替
np.asarray(a)==1
.
样本运行-
In [81]: a
Out[81]: [0, 0, 1, 1, 0, 1, 0, 1, 0, 0]
In [82]: m = np.r_[False,np.asarray(a)==1,False]
...: idx = np.flatnonzero(m[:-1]!=m[1:])
...: out = idx[1::2]-idx[::2]
In [83]: out
Out[83]: array([2, 1, 1])