擅长:python、mysql、java
<p>按照nosklo的回答,我倾向于使用以下模式:</p>
<p>来自优秀<a href="http://docs.python.org/library/itertools.html#recipes" rel="noreferrer">itertools recipes</a>的函数<code>pairwise</code>非常适合:</p>
<pre><code>from itertools import tee
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = tee(iterable)
next(b, None)
return izip(a, b)
</code></pre>
<p>在代码中使用它可以让我们:</p>
<pre><code>for line, next_line in pairwise(file):
if next_line.startswith("0"):
pass #perform pre-processing
#...
pass #continue with normal processing
</code></pre>
<p>通常,对于这种类型的处理(iterable中的lookahead),我倾向于使用<a href="http://mail.python.org/pipermail/python-dev/2006-May/065304.html" rel="noreferrer">window function</a>。两厢是2号窗户的特例。</p>