2024-05-05 21:27:31 发布
网友
我有一个python for循环,在这个循环中,我需要查看一个项目,看看是否需要在处理之前执行一个操作。
for line in file: if the start of the next line == "0": perform pre-processing ... continue with normal processing ...
在python中有什么简单的方法可以做到这一点吗? 我目前的方法是将文件缓冲到一个数组中,但是这并不理想,因为文件很大。
您可以使用此配方获得任何可以预取下一个项目的项目:
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)
示例用法:
for line, next_line in get_next(myfile): if next_line and next_line.startswith("0"): ... do stuff
如果您想向前看2行或更多行,代码允许您将window参数作为更大的值传递。
window
按照nosklo的回答,我倾向于使用以下模式:
来自优秀itertools recipes的函数pairwise非常适合:
pairwise
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)
在代码中使用它可以让我们:
for line, next_line in pairwise(file): if next_line.startswith("0"): pass #perform pre-processing #... pass #continue with normal processing
通常,对于这种类型的处理(iterable中的lookahead),我倾向于使用window function。两厢是2号窗户的特例。
您可以有一个prev_line,在这里存储前一行,并在仅给定条件的情况下读取一行时处理该行。
prev_line
类似于:
prev_line = None for line in file: if prev_line is not None and the start of the next line == "0": perform pre-processing on prev_line ... continue with normal processing ... prev_line = line
如果需要,您可能需要对最后一行进行额外的处理,这取决于您的逻辑。
您可以使用此配方获得任何可以预取下一个项目的项目:
示例用法:
如果您想向前看2行或更多行,代码允许您将
window
参数作为更大的值传递。按照nosklo的回答,我倾向于使用以下模式:
来自优秀itertools recipes的函数
pairwise
非常适合:在代码中使用它可以让我们:
通常,对于这种类型的处理(iterable中的lookahead),我倾向于使用window function。两厢是2号窗户的特例。
您可以有一个
prev_line
,在这里存储前一行,并在仅给定条件的情况下读取一行时处理该行。类似于:
如果需要,您可能需要对最后一行进行额外的处理,这取决于您的逻辑。
相关问题 更多 >
编程相关推荐