如何在Python中的一行中输入2个整数?

ene*_*dil 9 python input line python-3.x

我想知道是否可以在一行标准输入中输入两个或更多整数.在C/ C++它很容易:

C++:

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

C:

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

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'
Run Code Online (Sandbox Code Playgroud)

那怎么办呢?

Mar*_*ers 20

在空白处拆分输入的文本:

a, b = map(int, input().split())
Run Code Online (Sandbox Code Playgroud)

演示:

>>> a, b = map(int, input().split())
3 5
>>> a
3
>>> b
5
Run Code Online (Sandbox Code Playgroud)

  • +1.这是为什么`map`和类似函数应保留在Python 3中的一个很好的例子.我只在左侧添加`,*rest`以使其更加健壮.具有列表推导的非地图版本也是可能的,但它不是那么干净:`a,b,*rest = [int(e)for e in input().split()]`. (3认同)

Dhr*_*gat 5

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

a, b = map(int, raw_input().split())
Run Code Online (Sandbox Code Playgroud)

  • 对不起,标签上写着“python 3”。您的代码在 Python 2 中有效。 py3 中的输入正是来自 py2 的 raw_input。 (2认同)