Python 检查列表中不定数量的连续元素是否满足条件

Python check if indefinite number of consecutive elements in a list satisfy a condition

基本上我在玩嵌套列表,并希望对于给定的输入 n,查找 n 中的连续元素该列表满足预定条件。

例如:

n = 3
lst = [[1,2,3],[6,7,8],[4,5,6],[1,3,4,5]]

而且我想知道 lst 中是否有 n 个长度大于或等于 3(或其他条件)的连续子列表。首先找到最有效的方法是什么:

  1. 是否满足条件
  2. 条件满足时索引范围n

我的说明性示例的示例输出是:

True
index_range = (0,2) #Only need the first instance when n consec achieved

任何帮助将不胜感激,最好是不太依赖内置 Python 库的代码,例如 itertoolsnumpy 因为我是 Python 的新手,想更好地了解这样一个过程是如何工作的。提前致谢!

lst = [[1,2,3],[6,7,8],[4,5,6],[1,3,4,5]]

def check_cond_func(lst, n):
    count = 0
    range = []
    for i, l in enumerate(lst):
        if count == n:
            break
        if len(l) != n:
            count = 0
        if len(l) == n:
            count += 1
            range.append(i)
    if count == n:
        return (True, (min(range), max(range)))
    else:
        return False

yay_nay, index_range = check_cond_func(lst, 3)
print(yay_nay)    
print(index_range)

输出

True
(0, 2)

允许设置不同的条件

def check(lst, conditional, n):
  " Checks for consective sublist satisfying conditional "

  for i in range(len(lst)):
    # Starting with i-th sublist
    for j in range(i, i+n):
      # checking for n consecutive sublists
      # where conditional(lst[j]) is True
      if not conditional(lst[j]):
        break
    else:
      return True, i, i+n-1
  return False

def condition(sublist):
  " Condiiton on length "
  return len(sublist) >= 3

lst = [[1,2,3],[6,7,8],[4,5,6],[1,3,4,5]]
print(check(lst, condition, 3))

# Out: (True, 0, 2)

不同的条件,一个循环,恒定的内存使用,提前退出

def func(lst, n, condition):
    n_consec = 0
    if len(lst) < n:
        return (False, None)
    for i,sub in enumerate(lst):
        if condition(sub):
            n_consec += 1
            if n_consec == n:
                return (True, (i-n+1, i))
        else:
            n_consec = 0
            if len(lst) - (i + 1) < n:
                return (False, None)
    return (False, None)

print(func(lst,n, lambda sub: len(sub) >= n))