连续值大于100的序列平均长度(Python)

2024-10-01 09:38:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图确定数组中连续序列的长度,这些序列的长度为>;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)

输出

Index :  12837 ,Length :  1879
Index :  6179 ,Length :  3474
Index :  1164 ,Length :  1236
Index :  2862 ,Length :  617

Tags: indexlenif序列lengthsequencemaxlenmaxidx
3条回答

你想找到所有的序列,计算它们的长度,得到平均值。这些步骤中的每一步都相对简单

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]), ...

查找长度(小心,不能列出可数项):

lens = [len(g) for k, g in groups if k]  # [1, 2, 3]

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

avg = float(sum(lens)) / len(lens)  # 2.0

这应该起作用:

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]

之后,你可以计算平均值或做任何你喜欢的事情

结果是:

>>> get_100_lengths( [120,120,120,90,90,120,90,120,120] )
[3, 1, 2]

这可能有点棘手。您希望使用一个变量来跟踪长度之和,使用一个变量来跟踪序列发生的次数。 我们可以确定当当前编号<;100且之前的数字大于100

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) 

未测试此代码,如果有任何问题,请发表评论

相关问题 更多 >