Python 计算2D列表中连续3的数量

Python 计算2D列表中连续3的数量,python,python-2.7,Python,Python 2.7,我作为列表导入python的数据集: 有没有办法计算出连续3秒的最大数量?与第一行一样,输出应该是5,因为有5个连续的3 import csv r = csv.reader(open('motor.csv')) list_r = list(r) for row in list_r: print count = 0 for col in row: if col == '3' and row[row.index(col)+1] == '3':

我作为列表导入python的数据集:

有没有办法计算出连续3秒的最大数量?与第一行一样,输出应该是5,因为有5个连续的3

import csv
r = csv.reader(open('motor.csv'))
list_r = list(r)


for row in list_r:
    print
    count = 0
    for col in row:
        if col == '3' and row[row.index(col)+1] == '3':
            count+=1

print count

这是我写的代码,但我似乎得到了不正确的输出。

他们将以下内容作为指导:

import itertools

def consecutive(group):
    first, second = itertools.tee(group)
    second.next()
    for first, second in itertools.izip(first, second):
        if second != first + 1:  return False
    return True

def iterate_submatrix(matrix, t, l):
    '''yield the horizontals and diagonals of 4x4  subsection of matrix starting at t(op), l(eft) as 4-tuples'''
    submat =  [row[l:l+4] for row in matrix[t:t+4]]
    for r in submat: yield tuple(r)  
    for c in range (0,4):     
        yield tuple(r[c] for r in submat)
    yield tuple(submat[rc][rc] for rc in range (0,4))
    yield tuple(submat[rc][3-rc] for rc in range(0,4))

for item in iterate_submatrix(test_matrix, 0,0):
     print item, consecutive(item)
首先,row.indexcol将始终生成该行中col的第一个值的索引。这显然不是本意。相反,我建议使用enumerate同时迭代行中的值和索引

其次,您只跟踪当前连续3的数量,没有代码跟踪此计数值的最大值。向代码中添加另一个变量和else子句可以解决此问题

for row in list_r:
    max_count = current_count = 0
    for index, value in enumerate(row[:-1]):
        if value == '3' and row[index+1] == '3':
            current_count += 1
        else:
            max_count = max(current_count, max_count)
            current_count = 0
    print count
考虑使用itertools.groupby将列表拆分为具有相同值的子序列。然后简单地返回子序列的最大长度

from itertools import groupby
list_r = [
    ['3','3','3','3','3','1','3','3','5'],
    ['1','2','3','3','3','3','3','3','1','3','3','5','3'],
    ['3','2','3','3','3','3','3','3','1','3','3','5'],
]

result = [
    max(len(list(g)) for k, g in groupby(row) if k == '3')
    for row in list_r
]

assert result == [5, 6, 6]

将list_r的实际值作为文本在代码中发布,因此我们不需要motor.csv,因为它看起来像是在计算同一行中相邻两对的数量。如果有人让我找到最连续的3,我不会这么想。此外,在每行之后重置计数,但不打印结果直到完成。考虑当行中有多于一个“3”时,ROW.RealXCOL的值是什么。
import re

data = [
    ['1', '2', '2', '3', '5', '6'],
    ['1', '2', '3', '3', '4', '5'],
    ['1', '2', '3', '3', '3', '4']
]

max = 0
for item in data:
    match = re.search(r'3+', "".join(item))

try:

    if len(str(match.group(0))) > max:
        max = len(str(match.group(0)))
except AttributeError:
    pass

print(max)