簡體   English   中英

如何在 Python 中輸入矩陣(二維列表)?

[英]How to input matrix (2D list) in Python?

我嘗試創建此代碼以輸入 m x n 矩陣。 我打算輸入[[1,2,3],[4,5,6]]但代碼產生[[4,5,6],[4,5,6] 當我輸入其他 m × n 矩陣時,會發生同樣的事情,代碼生成一個 m × n 矩陣,其行相同。

也許你可以幫我找出我的代碼有什么問題。

m = int(input('number of rows, m = '))
n = int(input('number of columns, n = '))
matrix = []; columns = []
# initialize the number of rows
for i in range(0,m):
  matrix += [0]
# initialize the number of columns
for j in range (0,n):
  columns += [0]
# initialize the matrix
for i in range (0,m):
  matrix[i] = columns
for i in range (0,m):
  for j in range (0,n):
    print ('entry in row: ',i+1,' column: ',j+1)
    matrix[i][j] = int(input())
print (matrix)

問題出在初始化步驟上。

for i in range (0,m):
  matrix[i] = columns

這段代碼實際上使matrix每一行都指向相同的columns對象。 如果任何列中的任何項目發生更改 - 每隔一列都會更改:

>>> for i in range (0,m):
...     matrix[i] = columns
... 
>>> matrix
[[0, 0, 0], [0, 0, 0]]
>>> matrix[1][1] = 2
>>> matrix
[[0, 2, 0], [0, 2, 0]]

您可以在嵌套循環中初始化矩陣,如下所示:

matrix = []
for i in range(0,m):
    matrix.append([])
    for j in range(0,n):
        matrix[i].append(0)

或者,在單行中使用列表理解:

matrix = [[0 for j in range(n)] for i in range(m)]

或者:

matrix = [x[:] for x in [[0]*n]*m]

也可以看看:

希望有幫助。

您可以通過這種方式在python中接受二維列表...

簡單地

arr2d = [[j for j in input().strip()] for i in range(n)] 
# n is no of rows


對於字符

n = int(input().strip())
m = int(input().strip())
a = [[0]*n for _ in range(m)]
for i in range(n):
    a[i] = list(input().strip())
print(a)

或者

n = int(input().strip())
n = int(input().strip())
a = []
for i in range(n):
    a[i].append(list(input().strip()))
print(a)

對於數字

n = int(input().strip())
m = int(input().strip())
a = [[0]*n for _ in range(m)]
for i in range(n):
    a[i] = [int(j) for j in input().strip().split(" ")]
print(a)

其中 n 是列中的元素數,而 m 是行中的元素數。

以pythonic的方式,這將創建一個列表列表

如果您想輸入 n 行,其中每行包含 m 個空格分隔的整數,例如:

1 2 3
4 5 6 
7 8 9 

然后你可以使用:

a=[] // declaration 
for i in range(0,n):   //where n is the no. of lines you want 
 a.append([int(j) for j in input().split()])  // for taking m space separated integers as input

然后為上述輸入打印您想要的任何內容:

print(a[1][1]) 

對於基於 0 的索引,O/P 將為 5

如果輸入的格式是這樣的,

1 2 3
4 5 6
7 8 9

可以使用單襯

mat = [list(map(int,input().split())) for i in range(row)]

除了接受的答案,您還可以通過以下方式初始化您的行 - matrix[i] = [0]*n

因此,以下代碼將起作用-

m = int(input('number of rows, m = '))
n = int(input('number of columns, n = '))
matrix = []
# initialize the number of rows
for i in range(0,m):
    matrix += [0]
# initialize the matrix
for i in range (0,m):
    matrix[i] = [0]*n
for i in range (0,m):
    for j in range (0,n):
        print ('entry in row: ',i+1,' column: ',j+1)
        matrix[i][j] = int(input())
print (matrix)

此代碼從用戶獲取行數和列數,然后獲取元素並顯示為矩陣。

m = int(input('number of rows, m : '))
n = int(input('number of columns, n : '))
a=[]
for i in range(1,m+1):
  b = []
  print("{0} Row".format(i))
  for j in range(1,n+1):
    b.append(int(input("{0} Column: " .format(j))))
  a.append(b)
print(a)

如果您的矩陣以如下行方式給出,其中大小為 s*s 此處 s=5 5 31 100 65 12 18 10 13 47 157 6 100 113 174 11 33 88 124 41 20 140 99 32 111 41 20

那么你可以使用這個

s=int(input())
b=list(map(int,input().split()))
arr=[[b[j+s*i] for j in range(s)]for i in range(s)]

你的矩陣將是 'arr'

m,n=map(int,input().split()) # m - 行數; n - 列數;

矩陣 = [[int(j) for j in input().split()[:n]] for i in range(m)]

對於矩陣中的 i:print(i)

no_of_rows = 3  # For n by n, and even works for n by m but just give no of rows
matrix = [[int(j) for j in input().split()] for i in range(n)]
print(matrix)

您可以制作任何維度的列表

list=[]
n= int(input())
for i in range(0,n) :
    #num = input()
    list.append(input().split())
print(list)

輸出:

代碼顯示與輸出

rows, columns = list(map(int,input().split())) #input no. of row and column
b=[]
for i in range(rows):
    a=list(map(int,input().split()))
    b.append(a)
print(b)

輸入

2 3
1 2 3
4 5 6

輸出[[1, 2, 3], [4, 5, 6]]

a = []
b = []

m=input("enter no of rows: ")
n=input("enter no of coloumns: ")

for i in range(n):
     a = []
     for j in range(m):
         a.append(input())
     b.append(a)

輸入:1 2 3 4 5 6 7 8 9

輸出: [ ['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9'] ]

可以使用列表理解來創建帶有預填充數字的矩陣。 它可能很難閱讀,但它可以完成工作:

rows = int(input('Number of rows: '))
cols = int(input('Number of columns: '))
matrix = [[i + cols * j for i in range(1, cols + 1)] for j in range(rows)]

2行3列矩陣為[[1, 2, 3], [4, 5, 6]], 3行2列矩陣為[[1, 2], [3, 4], [ 5, 6]] 等。

row=list(map(int,input().split())) #input no. of row and column
b=[]
for i in range(0,row[0]):
    print('value of i: ',i)
    a=list(map(int,input().split()))
    print(a)
    b.append(a)
print(b)
print(row)

輸出:

2 3

value of i:0
1 2 4 5
[1, 2, 4, 5]
value of i:  1
2 4 5 6
[2, 4, 5, 6]
[[1, 2, 4, 5], [2, 4, 5, 6]]
[2, 3]

注意:此代碼在控制的情況下。它只控制沒有。 行,但我們可以輸入我們想要的任意數量的列,即row[0]=2所以要小心。 這不是您可以控制列數的代碼。

a,b=[],[]
n=int(input("Provide me size of squre matrix row==column : "))
for i in range(n):
   for j in range(n):
      b.append(int(input()))
    a.append(b)
    print("Here your {} column {}".format(i+1,a))
    b=[]
for m in range(n):
    print(a[m])

完美運行

我使用了 numpy 庫,它對我來說很好用。 它只是一行並且易於理解。 輸入需要是由空格分隔的單一大小,reshape 會將列表轉換為您想要的形狀。 這里 (2,2) 將 4 個元素的列表調整為 2*2 矩陣。 在輸入中給出與矩陣維度相對應的相同數量的元素時要小心。

import numpy as np
a=np.array(list(map(int,input().strip().split(' ')))).reshape(2,2)

print(a)

輸入

array([[1, 2],
       [3, 4]])

輸出

暫無
暫無

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

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