Python中for循环预读

21 投票
7 回答
13484 浏览
提问于 2025-04-16 07:10

我有一个Python的for循环,在这个循环里,我需要提前看一下下一个项目,看看是否需要在处理之前执行某个操作。

for line in file:
    if the start of the next line == "0":
        perform pre-processing
        ...
    continue with normal processing
    ...

有没有什么简单的方法可以在Python中做到这一点呢?我现在的方法是把文件缓冲到一个数组里,但这样做并不好,因为文件比较大。

7 个回答

10

你可以用一个叫 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

如果需要的话,你可能还需要对最后一行做一些额外的处理,这要看你的逻辑。

12

根据nosklo的回答,我通常会使用以下的模式:

来自优秀的itertools食谱的函数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

一般来说,对于这种处理方式(在可迭代对象中向前查看),我倾向于使用窗口函数。而pairwise就是一个大小为2的窗口的特例。

20

你可以用这个方法让任何可迭代的对象提前获取下一个项目:

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

这段代码允许你把 window 参数设置得更大,如果你想提前查看两行或更多行。

撰写回答