more_itertools
有幾個lookahead tools的一個特例。這裏我們將演示一些用於處理文件行的工具和抽象函數。鑑於:
f = """\
A
B
C
0
D\
"""
lines = f.splitlines()
代碼
import more_itertools as mit
def iter_lookahead(iterable, pred):
# Option 1
p = mit.peekable(iterable)
try:
while True:
line = next(p)
next_line = p.peek()
if pred(next_line):
# Do something
pass
else:
print(line)
except StopIteration:
return
pred = lambda x: x.startswith("0")
iter_lookahead(lines, pred)
輸出
A
B
0
下面是包括由@Muhammad Alkarouri提到pairwise
和windowed
工具等選項使用相同的庫。
# Option 2
for line, next_line in mit.pairwise(lines):
if pred(next_line):
# Do something
pass
else:
print(line)
# Option 3
for line, next_line in mit.windowed(lines, 2):
if pred(next_line):
# Do something
pass
else:
print(line)
後面的選項可以獨立運行或替代先前函數中的邏輯。
是否會導致它從文件中讀取兩次,或者是否以某種方式緩衝該行? – Mike 2010-11-16 19:09:12
它只讀一次。請參見['itertoolsmodule.c']中的'teedataobject_getitem'(http://svn.python.org/projects/python/branches/release27-maint/Modules/itertoolsmodule.c) – 2010-11-16 19:14:44
您的'get_next'在itertools receipes中['pairwise'](http://docs.python.org/library/itertools.html#recipes) – 2010-11-16 19:18:46