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

时间:2019-01-04 10:18:41

标签: python list

我有一个列表o整数列表,例如下面的例子:

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

并且我想获得每个子列表中连续偶数的最大长度作为输出, 输出列表是:

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

这是我的代码:

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

但是此代码是错误的。

4 个答案:

答案 0 :(得分:4)

让我们保持简单。您将需要两个循环。您还需要一个计数器来跟踪当前计数。为简单起见,您可以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]

答案 1 :(得分:3)

您可以使用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)

输出

[1, 2, 3, 0, 3]

答案 2 :(得分:1)

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]

答案 3 :(得分:0)

我将定义一个可以处理条件的辅助方法:

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

要用于列表理解:

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]