简体   繁体   English

满足给定条件的列表中连续元素的计数

[英]Count of consecutive elements in a list that satisfy a given condition

i have a list o lists of integers for example such a below: 我有一个列表或整数列表,例如下面这样的列表:

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

and i want to get maximum length of consecutive even numbers in each sublist as output, output list is: 我想在每个子列表中获得连续偶数的最大长度作为输出,输出列表是:

  olist = [1,2,3,0,3]

and this is my code: 这是我的代码:

olist=[]
for ii in list1:
    if all(item % 2 == 0 for item in ii):
        olist.append(len(ii))
print (olist)

but this code is wrong. 但是这段代码是错误的。

Let's keep this simple. 让我们保持简单。 You will need two loops. 您将需要两个循环。 You will also need a counter to keep track of the current count. 您还需要一个计数器来跟踪当前计数。 You can have tr keep track of the largest count, for simplicity. 你可以有tr跟踪计数最大的,为了简单起见。

tr = [0] * len(lst)
for i, l in enumerate(lst):
    counter = 0
    for v in l:
        if v % 2 == 0:
            counter += 1
        else:
            tr[i] = max(counter, tr[i])
            counter = 0
    tr[i] = max(counter, tr[i])

print(tr)
# [1, 2, 3, 0, 3]

You can use itertools.groupby to group the numbers in even / odd groups then get the even group with maximum length using max: 您可以使用itertools.groupby将数字分组为偶数/奇数组,然后使用max获得最大长度的偶数组:

from itertools import groupby

def max_even(lst):
    result = []
    for e in lst:
        it = (sum(1 for _ in group) for k, group in groupby(e, lambda x: x % 2) if not k)
        m = max(it, default=0)
        result.append(m)
    return result

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

res = max_even(l)
print(res)

Output 输出量

[1, 2, 3, 0, 3]
myList = [[1,2,3],[1,2,5,6,8],[2,4,6,9,7],[1,3],[2,4,3,6,8,2]]
outList = []
for i in myList:
    max_Length = 0
    myLength = 0
    interim_list = []
    for j in i:
        if j%2 == 0:
            myLength = myLength + 1
            if myLength > max_Length:
                max_Length = myLength
        else:
            myLength = 0
    outList.append(max_Length)
outList    
    [1,2,3,0,3]

I'd define a helper method that can handle a condition: 我将定义一个可以处理条件的辅助方法:

def max_consecutive(array, odd_even):
  remainder = {'odd':1,'even':0}
  count, max_count = 0, 0
  for e in array:
    if e%2 == remainder[odd_even]:
      count +=1
    else:
      count = 0
    max_count = max(count, max_count)
  return max_count

To be used in a list comprehension: 要用于列表理解中:

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

[max_consecutive(sub, 'even') for sub in array]
#=> [1, 2, 3, 0, 3]

[max_consecutive(sub, 'odd') for sub in array]
#=> [1, 1, 2, 2, 1]

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

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