擅长:python、mysql、java
<p>您可以使用此配方获得任何可以预取下一个项目的项目:</p>
<pre><code>from itertools import tee, islice, izip_longest
def get_next(some_iterable, window=1):
items, nexts = tee(some_iterable, 2)
nexts = islice(nexts, window, None)
return izip_longest(items, nexts)
</code></pre>
<p>示例用法:</p>
<pre><code>for line, next_line in get_next(myfile):
if next_line and next_line.startswith("0"):
... do stuff
</code></pre>
<p>如果您想向前看2行或更多行,代码允许您将<code>window</code>参数作为更大的值传递。</p>