使用 sys.stdin 来比较 python 中的 2 行?

Use sys.stdin to compare 2 lins in python?

我正在使用 python 做我的 MapReduce 作业,它将使用 sys.stdin 作为输入文件的 reader。例如:

for line in sys.stdin:
     # compare 1st line with the 2ed line.

我可以将所有文件内容加载到内存中并使用索引实现 2 行比较,例如:

lines= open("guru99.txt","r")
for i in range(len(lines)):
    if lines[i] != lines[i-1]:
       ...

我的问题是如何使用 sys.stdin 方式比较这两行?由于作业文件“guru99.txt”很大,我无法将其加载到内存中,但只有sys.stdin方式才有效。

您可以使用 next 获取第一行,然后迭代剩余的输入。

import sys

try:
    prev = next(sys.stdin)
except StopIteration:
    # no input
    exit()

for line in sys.stdin:
    if line == prev:
        do the things
    prev = line