1

我有一个数组,其值如下:

list1=[0,0,1,1,14,4,3,0,0,0,1,4,3]

我想找到该数组中 x > 0 的运行长度。所以输出将类似于:

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

这是接近它的正确方法吗?

4

4 回答 4

3

当您只有输入和输出时,很难确定“这是处理它的正确方法吗?”。这取决于你想回答什么。但这里是对 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]
于 2013-10-21T00:01:08.330 回答
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)
于 2013-10-20T23:09:22.200 回答
1
runs, c = [], 0
for x in list1 + [0]:
    if x:
        c += 1
    elif c:
        runs.append(c)
        c = 0
于 2013-10-21T00:04:49.410 回答
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
于 2013-10-20T23:56:30.743 回答