我有一个数组,其值如:
list1=[0,0,1,1,14,4,3,0,0,0,1,4,3]
我想找到该数组中的运行长度,其中x>所以输出将是这样的:
runs = [5,3]
这是我到目前为止所做的,但不知道如何继续:
runs = []
curr = 0
for x in list1:
while x > 0:
curr += 1
#Not sure where to go from here. Somehow append curr to runs and
reset curr once the run is over
这是接近它的正确方法吗?
答案 0 :(得分:2)
runs = []
curr = 0
for x in list1:
if x == 0:
if curr != 0:
runs.append(curr)
curr = 0
else:
curr = curr + 1
if curr > 0: runs.append(curr)
答案 1 :(得分:2)
当你所拥有的只是输入和输出时,很难确定答案“这是接近它的正确方法吗?”。这取决于你想要回答什么。但这是对DSM建议的修改。
import itertools as it
l=[0,0,1,1,14,4,3,0,0,0,1,4,3]
[len(list(cgen)) for c,cgen in it.groupby(l, lambda x: x>0) if c]
答案 2 :(得分:1)
runs, c = [], 0
for x in list1 + [0]:
if x:
c += 1
elif c:
runs.append(c)
c = 0
答案 3 :(得分:0)
def foo(arr):
cur=[]
index1=0
while index1<len(arr):
if arr[index1]!=0:
index2=index1
while index2!=0 and index2<len(arr):
index2+=1
cur.append(index2-index1)
index1=index2
else:
index1+=1
return cur