python stdin with txt file and input() function



我有一个输入.txt文件,其中包含以下内容。

3 
4 5

我想通过在命令行中使用以下命令将其用作标准输入。

python a.py < input.txt

在 a.py 脚本中,我尝试使用input()函数逐行读取输入。我知道有更好的方法来读取标准,但我需要使用input()函数。

一种幼稚的方法

line1 = input()
line2 = input()

没有用。我收到以下错误消息。

File "<string>", line 1
4 5
^
SyntaxError: unexpected EOF while parsing

这样没关系,它有效:

read = input()
print(read)

但你只是在读一行。

从输入((文档:

然后,该函数从输入中读取一行,将其转换为字符串 (去掉尾随换行符(,并返回该换行符。

这意味着,如果文件不以空行结尾,或者相同,则文件的最后一个非空行不以end of line字符结尾,您将得到exceptions.SyntaxError并且最后一行不会被读取。

你提到了HackerRank;看看我的一些旧提交,我想我选择放弃input而不是sys.stdin操纵。input()next(sys.stdin)非常相似,但后者可以很好地处理EOF。

举个例子,我对 https://www.hackerrank.com/challenges/maximize-it/的回答

import sys
import itertools
# next(sys.stdin) is functionally identical to input() here
nK, M = (int(n) for n in next(sys.stdin).split())
# but I can also iterate over it
K = [[int(n) for n in line.split()][1:] for line in sys.stdin]
print(max(sum(x**2 for x in combo) % M for combo in itertools.product(*K)))

最新更新