简体   繁体   English

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

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

Basically I am playing around with nested lists, and would like for a given input n , to find if n consecutive elements in the list satisfy a predetermined condition.基本上我正在玩嵌套列表,并希望对于给定的输入n ,以查找列表中的n个连续元素是否满足预定条件。

For example:例如:

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

And I would like to know if there are n consecutive sublists within lst that have length greater than or equal to 3 (Or some other condition).而且我想知道 lst 中是否有n个长度大于或等于 3 的连续子列表(或其他一些条件)。 What is the most efficient way to find firstly:首先找到最有效的方法是什么:

  1. Is the condition satisfied是否满足条件
  2. The range of indices for when condition is satisfied n times条件满足n次时的指标范围

An example output for my illustrative example would be:对于我的说明性示例,示例 output 将是:

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

Any help would be greatly appreciated, preferably code which doesn't rely too heavily on inbuilt Python libraries such as itertools or numpy as I am new to Python and would like to better understand how such a process works.任何帮助将不胜感激,最好是不太依赖内置 Python 库(例如itertoolsnumpy )的代码,因为我是 ZA7F5F35426B927411FC9231B563821 的新手,并希望更好地理解这样的过程。 Thanks in advance!提前致谢!

different conditionals, one loop, constant memory usage, early exiting不同的条件,一个循环,恒定的 memory 用法,提前退出

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))
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)

Output Output

True
(0, 2)

Allows setting different conditionals允许设置不同的条件

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM