使用 Python 遍历文件时请参考上一行

The*_*man 2 python

我有一个如下所示的循环:

with open(file, 'r') as f:
    next(f)
    for line in f:
        print line
Run Code Online (Sandbox Code Playgroud)

但我不想在每次迭代时只打印当前行,我还想打印前一行,如下所示,但代码没有给我我正在寻找的内容:

with open(file, 'r') as f:
    next(f)
    for line in f:
        previous(f)    #this does not go to the previous line
        print line
        next(f)
        print line
        next(f)
Run Code Online (Sandbox Code Playgroud)

结果应该是这样的:

输入:

line1
line2
line3
Run Code Online (Sandbox Code Playgroud)

输出:

line1
line2
line2
line3
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 5

迭代器只能前进,所以没有previous()功能。

只需将当前行存储在一个变量中;它将是下一次迭代的前一个:

with open(file, 'r') as f:
    previous = next(f)
    for line in f:
        print previous, line
        previous = line
Run Code Online (Sandbox Code Playgroud)