[英]Counting the number of consecutive 3s in a 2D list
考慮使用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]
他們將以下內容用作指導:
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.index(col)
將始終生成該行中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
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.