我有一个问题,因为我找不到解决问题的办法。
gen是一个生成器(difflib.Differ.compare()的结果):
通常,通过迭代gen,我可以读取每一行。问题是,在每次迭代中,我需要读取当前行和下两行。
示例(逐行迭代的正常输出):
iteration 1:
line = 'a'
iteration 2:
line = 'b'
iteration 3:
line = 'c'
iteration 4:
line = 'd'
iteration 5:
line = 'e'
iteration 6:
line = 'f'
iteration 7:
line = 'g'
但在我的例子中,我需要得到这个:
iteration 1:
line = 'a'
next1 = 'b'
next2 = 'c'
iteration 2:
line = 'b'
next1 = 'c'
next2 = 'd'
iteration 3:
line = 'c'
next1 = 'd'
next2 = 'e'
iteration 4:
line = 'd'
next1 = 'e'
next2 = 'f'
iteration 5:
line = 'e'
next1 = 'f'
next2 = 'g'
iteration 6:
line = 'f'
next1 = 'g'
next2 = None
iteration 7:
line = 'g'
next1 = None
next2 = None
我试着使用gen.send(),itertools.islice(),但是我找不到合适的解决方案。我不想将这个生成器转换为列表(然后我可以将next1读作geni + 1,将next2读作geni + 2,但当diff输出很大时,这是完全低效的。
发布于 2012-12-06 05:12:25
你可以使用类似这样的东西:
def genTriplets(a):
first = a.next()
second = a.next()
third = a.next()
while True:
yield (first, second, third)
first = second
second = third
try:
third = a.next()
except StopIteration:
third = None
if (first is None and second is None and third is None):
break
https://stackoverflow.com/questions/13732036
复制相似问题