连续值序列的平均长度>;100(Python)

连续值序列的平均长度>;100(Python),python,python-3.x,Python,Python 3.x,我试图确定数组中大于100的连续序列的长度。我已经使用下面的代码找到了最长的序列,但需要修改以找到平均长度 def getLongestSeq(a, n): maxIdx = 0 maxLen = 0 currLen = 0 currIdx = 0 for k in range(n): if a[k] >100: currLen +=1 # New sequence, store

我试图确定数组中大于100的连续序列的长度。我已经使用下面的代码找到了最长的序列,但需要修改以找到平均长度

def getLongestSeq(a, n): 
    maxIdx = 0
    maxLen = 0
    currLen = 0
    currIdx = 0
    for k in range(n): 
        if a[k] >100: 
            currLen +=1
             # New sequence, store 
            # beginning index. 
            if currLen == 1: 
                currIdx = k 
        else: 
            if currLen > maxLen: 
                maxLen = currLen 
                maxIdx = currIdx 
            currLen = 0

    if maxLen > 0: 
        print('Index : ',maxIdx,',Length : ',maxLen,) 
    else: 
        print("No positive sequence detected.") 

# Driver code 
arrQ160=resultsQ1['60s']
n=len(arrQ160)
getLongestSeq(arrQ160, n)

arrQ260=resultsQ2['60s']
n=len(arrQ260)
getLongestSeq(arrQ260, n)

arrQ360=resultsQ3['60s']
n=len(arrQ360)
getLongestSeq(arrQ360, n)

arrQ460=resultsQ4['60s']
n=len(arrQ460)
getLongestSeq(arrQ460, n)
输出

这应该起作用:

def get_100_lengths( arr ) :
    s = ''.join( ['0' if i < 100 else '1' for i in arr] )
    parts = s.split('0')
    return [len(p) for p in parts if len(p) > 0]

这可能有点棘手。您希望使用一个变量来跟踪长度之和,使用一个变量来跟踪序列发生的次数。 我们可以确定当前编号为100时序列是否终止: 总长度+=1 最后一个值大于等于真值
elif number您希望找到所有序列,计算它们的长度,然后得到平均值。这些步骤中的每一步都相对简单

items = [1, 101, 1, 101, 101, 1, 101, 101, 101, 1]
查找序列:使用
groupby

from itertools import groupby
groups = groupby(items, lambda x: x > 100)  # (False, [1]), (True, [101]), ...
查找长度(小心,不能列出可数项):

查找平均值(假设至少有一个):


尽可能避免索引。使用python优秀的迭代特性,而不是平均长度是什么意思?什么的长度?哇,我没有想过这个方法,这很有趣,lenik,如果我现在想知道每一个的索引,这样我就可以计算出它们之间的时间?因此,对于你上面的例子,我会得到[0:3,5:1,7:2]@Jake你可能想问另一个问题,因为这似乎是一个有点不同的问题,需要一个有点不同的解决方案谢谢你的回答和花费的时间!我最终使用了lenik提供的方法,效果非常好。
def getLongestSeq(array): 
    total_length = total_ct = 0
    last_is_greater = False 
    for number in array:
        if number > 100: 
            total_length += 1 
            last_is_greater = True
        elif number<100 and last_is_greater:
            total_ct += 1 
            last_is_greater = False 
    return round(total_length / total_ct) 
items = [1, 101, 1, 101, 101, 1, 101, 101, 101, 1]
from itertools import groupby
groups = groupby(items, lambda x: x > 100)  # (False, [1]), (True, [101]), ...
lens = [len(g) for k, g in groups if k]  # [1, 2, 3]
avg = float(sum(lens)) / len(lens)  # 2.0