代码之家  ›  专栏  ›  技术社区  ›  TheSohan

如何将整数流作为Python中的输入,就像我们在C++中所做的那样?

  •  -1
  • TheSohan  · 技术社区  · 6 年前

    here is sample test case for input

    C++代码

    while( cin >> variable)
     {
       //your code
     }
    

    我想把这段代码转换成python, 输入是整数流,如:

    2 回复  |  直到 6 年前
        1
  •  1
  •   AChampion    6 年前

    要在Python中实现相同,可以捕获 EOFError ,例如:

    while True:
        try:
            variable = int(input())
        except EOFError:
            break
        # your code
    

    您可以手动终止输入列表。 Ctrl-D 或者,如果您输入管道,它将自动终止,例如。 cat nums | myscript.py

        2
  •  0
  •   J...S    6 年前

    使用

    s=input("Enter: ")
    s=[int(x) for x in s.split()]
    

    input() 将返回输入的字符串版本。 split() 以空格作为分隔符应用于此字符串。

    由返回的列表中的每个元素 分裂() 转换为整数 int()

    编辑:

    要接受输入直到EOF,您可以

    import sys
    s=sys.stdin.read()
    if(s[-1]=='\n'):
        s=s[:-1]
    s=[int(x) for x in s.split()]