您还可以以一次获得 3 个项目的方式构建您的迭代,例如使用itertools 模块中的这个配方
from itertools import izip_longest
def grouper(iterable, n, fillvalue=None):
"Collect data into fixed-length chunks or blocks"
# grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return izip_longest(*args, fillvalue=fillvalue)
例如
>>> for x in grouper(xrange(10),3):
print x
(0, 1, 2)
(3, 4, 5)
(6, 7, 8)
(9, None, None)
>>>
所以对于你的情况,你可以这样做
lines = content.split("\n")
for line,x,y in grouper(lines,3):
...
if not isRecord(keyword) :
continue # go to the next iteration
或者如果内容不是纯 3 行块中的格式,则使用配方
from itertools import islice
import collections
def consume(iterator, n):
"Advance the iterator n-steps ahead. If n is none, consume entirely."
# Use functions that consume iterators at C speed.
if n is None:
# feed the entire iterator into a zero-length deque
collections.deque(iterator, maxlen=0)
else:
# advance to the empty slice starting at position n
next(islice(iterator, n, n), None)
例子
>>> it=iter(xrange(10))
>>> consume(it,5)
>>> list(it)
[5, 6, 7, 8, 9]
>>>
如果你真的需要,你也可以enumerate
用来知道你是谁,例如
lines = content.split("\n")
iterator = iter(enumerate(lines))
for i,line in iterator:
...
if not isRecord(keyword) :
consume(iterator,2)