如何在 Python 中输入矩阵(二维列表)? [英] How to input matrix (2D list) in Python?
问题描述
我尝试创建此代码以输入 m × n 矩阵.我打算输入 [[1,2,3],[4,5,6]]
但代码产生 [[[4,5,6],[4,5,6]]代码>.当我输入其他 m × n 矩阵时,会发生同样的事情,代码生成一个 m × n 矩阵,其行相同.
也许你可以帮我找出我的代码有什么问题.
m = int(input('行数,m = '))n = int(input('列数,n = '))矩阵 = [];列 = []# 初始化行数对于范围内的 i (0,m):矩阵 += [0]# 初始化列数对于范围 (0,n) 中的 j:列 += [0]# 初始化矩阵对于 i 在范围 (0,m) 中:矩阵[i] = 列对于 i 在范围 (0,m) 中:对于范围 (0,n) 中的 j:打印('行中的条目:',i+1,'列:',j+1)矩阵[i][j] = int(input())打印(矩阵)
问题出在初始化步骤.
for i in range (0,m):矩阵[i] = 列
这段代码实际上使 matrix
的每一行都指向同一个 columns
对象.如果任何列中的任何项目发生更改 - 每隔一列都会更改:
您可以在嵌套循环中初始化矩阵,如下所示:
矩阵 = []对于范围内的 i (0,m):矩阵.附加([])对于范围内的 j (0,n):矩阵[i].append(0)
或者,在单行中使用列表理解:
matrix = [[0 for j in range(n)] for i in range(m)]
或:
matrix = [x[:] for x in [[0]*n]*m]
另见:
希望有所帮助.
I tried to create this code to input an m by n matrix. I intended to input [[1,2,3],[4,5,6]]
but the code yields [[4,5,6],[4,5,6]
. Same things happen when I input other m by n matrix, the code yields an m by n matrix whose rows are identical.
Perhaps you can help me to find what is wrong with my code.
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)
The problem is on the initialization step.
for i in range (0,m):
matrix[i] = columns
This code actually makes every row of your matrix
refer to the same columns
object. If any item in any column changes - every other column will change:
>>> 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]]
You can initialize your matrix in a nested loop, like this:
matrix = []
for i in range(0,m):
matrix.append([])
for j in range(0,n):
matrix[i].append(0)
or, in a one-liner by using list comprehension:
matrix = [[0 for j in range(n)] for i in range(m)]
or:
matrix = [x[:] for x in [[0]*n]*m]
See also:
Hope that helps.
这篇关于如何在 Python 中输入矩阵(二维列表)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!