Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/344.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何处理多个输入行?_Python_Python 3.x - Fatal编程技术网

Python 如何处理多个输入行?

Python 如何处理多个输入行?,python,python-3.x,Python,Python 3.x,我尝试输出1-12行的总和,每行包含由“”分隔的两个数字。因为我不知道将输入多少行,所以我有一个无止境的循环,如果该行为空,循环将被中断。但是如果不再有输入,就不会有任何空的输入,程序就会被卡在输入函数中 while True: line = input() if line: line = line.split(' ') print(str(int(line[0]) + int(line[1]))) else: break

我尝试输出1-12行的总和,每行包含由“”分隔的两个数字。因为我不知道将输入多少行,所以我有一个无止境的循环,如果该行为空,循环将被中断。但是如果不再有输入,就不会有任何空的输入,程序就会被卡在输入函数中

while True:
    line = input()
    if line:
        line = line.split(' ')
        print(str(int(line[0]) + int(line[1])))
    else:
        break

所以在最后一次输出总和之后,我希望程序停止。可能有时间限制吗?

对于没有超时的案例,以及允许您捕获内容的案例(通常很方便)

以下代码已在HACKERRANK中测试。我相信哈克瑞斯是一样的

contents = []
while True:
    try:
        line = input()
        line = line.split(' ')
        print(str(int(line[0]) + int(line[1])))
    except EOFError:
        break
    contents.append(line)
如果你不在乎输入

while True:
    try:
        line = input()
        line = line.split(' ')
        print(str(int(line[0]) + int(line[1])))
    except EOFError:
        break

看起来自动输入是通过
sys.stdin
输入的。在这种情况下,您可以直接从标准输入流中读取。试试这个:

def main():
    import sys

    lines = sys.stdin.read().splitlines()
    for line in lines:
        print(sum(map(int, line.split())))

    return 0


if __name__ == "__main__":
    import sys
    sys.exit(main())

sys.stdin
流中输入“1 2\n3 4”时,此脚本在CLI的交互式提示中打印
3
7

超时是非常罕见的。你确定要这个吗?通常,您会等待用户输入内容或中止(通过发送EOF(ctrl+d)、sigint(ctrl+c)或输入空值)。这是hackerearth的做法,有自动输入,我无法编辑输入。因此,例如,输入是:1 2\n 21 5检查我的答案,看看它是否对您有效