如何在 Python 中的一行中输入 2 个整数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23253863/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to input 2 integers in one line in Python?
提问by enedil
I wonder if it is possible to input two or more integer numbers in one line of standard input. In C
/C++
it's easy:
我想知道是否可以在一行标准输入中输入两个或多个整数。在C
/C++
很容易:
C++
:
C++
:
#include <iostream>
int main() {
int a, b;
std::cin >> a >> b;
return 0;
}
C
:
C
:
#include <stdio.h>
void main() {
int a, b;
scanf("%d%d", &a, &b);
}
In Python
, it won't work:
在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'
So how to do it?
那么怎么做呢?
采纳答案by Martijn Pieters
Split the entered text on whitespace:
在空白处拆分输入的文本:
a, b = map(int, input().split())
Demo:
演示:
>>> a, b = map(int, input().split())
3 5
>>> a
3
>>> b
5
回答by Dhruv Bhagat
If you are using Python 2, then the answer provided by Martijn does not work. Instead, use:
如果您使用的是 Python 2,那么 Martijn 提供的答案不起作用。相反,使用:
a, b = map(int, raw_input().split())