【问题标题】:How to input 2 integers in one line in Python?如何在 Python 的一行中输入 2 个整数?
【发布时间】:2014-04-23 19:47:06
【问题描述】:

我想知道是否可以在一行标准输入中输入两个或多个整数。在C/C++ 这很简单:

C++:

#include <iostream>
int main() {
    int a, b;
    std::cin >> a >> b;
    return 0;
}

C:

#include <stdio.h>
void main() {
    int a, b;
    scanf("%d%d", &a, &b);
}

Python,它不起作用:

enedil@notebook:~$ cat script.py 
#!/usr/bin/python3
a = int(input())
b = int(input())
enedil@notebook:~$ python3 script.py 
3 5
Traceback (most recent call last):
  File "script.py", line 2, in <module>
    a = int(input())
ValueError: invalid literal for int() with base 10: '3 5'

那该怎么做呢?

【问题讨论】:

  • @Asad 是的。为什么不呢?
  • @Asad 你用什​​么编译器?我有gcc (Ubuntu 4.8.2-19ubuntu1) 4.8.2。有用。很好。
  • @RyanHaining 那里有一个空间。我不是 C 专家,但我认为除非输入是 35,否则这不会起作用。编辑:刚刚查了scanf,猜我错了。
  • @Asad 它适用于空格,而不是没有空格。自己编译并测试。

标签: python python-3.x input line


【解决方案1】:

在空格处分割输入的文本:

a, b = map(int, input().split())

演示:

>>> a, b = map(int, input().split())
3 5
>>> a
3
>>> b
5

【讨论】:

  • +1。这是为什么map 和类似函数应该保留在Python 3 中的一个很好的例子。我只会在左侧添加, *rest 以使其更健壮。具有列表理解的非地图版本也是可能的,但不是那么干净:a, b, *rest = [int(e) for e in input().split()].
  • input() 在 Pycharm ( Python 2.7 ) 中仍然不适合我。将其更改为 raw_input 以使其工作。
  • @blumonkey:这个问题是关于Python 3的。对于Python 2,你确实需要使用raw_input
  • @MartijnPieters 是否可以从多行获取相同的输入? a, b = map(int, input().split("\n")) 之类的东西?
  • @deppfx: input() 不能多行。使用循环。
【解决方案2】:

如果您使用的是 Python 2,那么 Martijn 提供的答案不起作用。相反,使用:

a, b = map(int, raw_input().split())

【讨论】:

  • 对不起,标签上写着“python 3”。您的代码在 Python 2 中有效。py3 中的输入正是来自 py2 的 raw_input。
【解决方案3】:
x,y = [int(v) for v in input().split()]
print("x : ",x,"\ty: ",y)

【讨论】:

    【解决方案4】:

    在python中,每次我们使用input()函数都会直接切换到下一行。要使用多个内联输入,我们必须使用split() 方法和input 函数,通过它我们可以获得所需的输出。

    a, b = [int(z) for z in input().split()]
    print(a, b)
    

    输入:

    3 4
    

    输出:

    3 4
    

    【讨论】:

      【解决方案5】:
      x, y = int(input()),  int(input())
      print("x : ",x,"\ty: ",y)
      

      【讨论】:

      • 这会提示输入分两行。问题是在 1 行中输入 2 个整数。
      • 它要求输入一行而不是一行代码:)
      猜你喜欢
      • 2015-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-10
      • 2018-08-04
      • 1970-01-01
      • 2021-04-02
      • 2019-07-31
      相关资源
      最近更新 更多