Python如何在一行輸入多個用戶值?

| | | | | | | | | | | | | | | |

// 讀取一行兩個值

scanf ( "%d%d" , &x,&y)

一種解決方法是使用兩次raw_input()。

x, y = raw_input (), raw_input ()

另一種解決方案是使用 split()

x, y = raw_input ()。 split()

注意我們不需要顯式指定 split (' '),因為 split() 默認使用任何空白字符作為分隔符。

在上面的 Python 代碼中,請注意 x 和 y 將是字符串。我們可以使用另一個字符串將它們轉換為 int

x, y = [int (x), int (y)] # 我們也可以使用  列表理解  x, y = [int (x) for x in [x, y] ] 

下面是使用拆分和

# 從輸入中讀取兩個數字並使用
# list comprehension

x, y = [ int (x) for x in raw_input (). split ()]


# 從輸入中讀取兩個數字並輸出to int using
#map function

x, y = map ( int , raw_input ().split())

請注意,在 Python 3 中,我們使用 input() 而不是 raw_input()。

本文由Abhishek Shukla 提供。如果您發現有問題或想分享有關討論主題的更多信息,請發表評論