我有一个问题,因为我找不到我的问题的解决方案。
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 读取为 gen[i + 1],将 next2 读取为 gen[i + 2],但是当 diff 输出很大时,这完全是低效的。