【发布时间】:2014-08-12 02:00:48
【问题描述】:
假设我在一个 numpy 数组中有一堆数字,我根据返回布尔数组的条件来测试它们:
np.random.seed(3456)
a = np.random.rand(8)
condition = a>0.5
通过这个布尔数组,我想计算 True 连续出现的所有长度。例如,如果我有[True,True,True,False,False,True,True,False,True],我想找回[3,2,1]。
我可以使用以下代码做到这一点:
length,count = [],0
for i in range(len(condition)):
if condition[i]==True:
count += 1
elif condition[i]==False and count>0:
length.append(count)
count = 0
if i==len(condition)-1 and count>0:
length.append(count)
print length
但是是否已经为此或 python、numpy、scipy 等函数实现了任何功能,用于计算给定输入的列表或数组中连续出现的长度?
【问题讨论】: