簡體   English   中英

如何在 Python 的一行中輸入 2 個整數?

[英]How to input 2 integers in one line in Python?

我想知道是否可以在一行標准輸入中輸入兩個或多個整數。 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'

那么該怎么做呢?

在空白處拆分輸入的文本:

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

演示:

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

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

a, b = map(int, raw_input().split())
x,y = [int(v) for v in input().split()]
print("x : ",x,"\ty: ",y)

在python中,每次我們使用input()函數時,它都會直接切換到下一行。 要使用多個內聯輸入,我們必須使用split()方法以及input函數,通過它我們可以獲得所需的輸出。

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

輸入:

3 4

輸出:

3 4

您可以在 Python 3 中使用 eval()。

n1,n2=eval(input("Enter two numbers "))

作為輸入,將兩個數字作為逗號分隔值傳遞

Enter two numbers 50,20
x, y = int(input()),  int(input())
print("x : ",x,"\ty: ",y)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM