【问题标题】:Use sys.stdin to compare 2 lins in python?使用 sys.stdin 比较 python 中的 2 行?
【发布时间】:2020-11-14 19:39:32
【问题描述】:

我正在使用 python 来完成我的 MapReduce 作业,它将使用 sys.stdin 作为输入文件的读取器。例如:

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 方式。

【问题讨论】:

  • 你能想出一种方法来记住前一行是什么,同时从循环中获取当前行吗?换句话说:你能想出一种方法来记住当前行是什么,以便 when 你从循环中获得 next 行,你将拥有这一行比较一下?
  • 一次输入两行?使用next(sys.stdin)

标签: python python-3.x mapreduce


【解决方案1】:

您可以使用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

【讨论】:

    猜你喜欢
    • 2014-10-29
    • 2016-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-26
    • 2017-06-15
    • 1970-01-01
    相关资源
    最近更新 更多