從 Python 使用者處獲取矩陣輸入


在本教程中,我們將學習如何從 Python 使用者處獲取矩陣輸入。我們可以透過兩種不同的方式從使用者處獲取輸入。讓我們來看一下這兩種方式。

方法 1

從使用者處逐個獲取矩陣的所有數字。請參閱以下程式碼。

示例

# initializing an empty matrix
matrix = []
# taking 2x2 matrix from the user
for i in range(2):
   # empty row
   row = []
   for j in range(2):
      # asking the user to input the number
      # converts the input to int as the default one is string
      element = int(input())
      # appending the element to the 'row'
      row.append(element)
   # appending the 'row' to the 'matrix'
   matrix.append(row)
# printing the matrix
print(matrix)

輸出

如果您執行以上程式碼,則會得到以下結果。

1
2
3
4
[[1, 2], [3, 4]]

矩陣 2

一次獲取一行帶有空格分隔的值。並使用 mapint 函式將它們轉換為。請參閱程式碼。

示例

# initializing an empty matrix
matrix = []
# taking 2x2 matrix from the user
for i in range(2):
   # taking row input from the user
   row = list(map(int, input().split()))
   # appending the 'row' to the 'matrix'
   matrix.append(row)
# printing the matrix
print(matrix)

輸出

如果您執行以上程式碼,則會得到以下結果。

1 2
3 4
[[1, 2], [3, 4]]

結論

如果您對教程有任何疑問,請在評論區中提及。

更新於: 2020 年 7 月 11 日

7K+ 次瀏覽

開啟你的 職業

透過完成課程獲得認證

開始
廣告宣傳
© . All rights reserved.