如何在 Python 中输入矩阵(二维列表)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22741030/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:34:14  来源:igfitidea点击:

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

pythonlistinputmatrix

提问by Iqazra

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.

我尝试创建此代码以输入 m x n 矩阵。我打算输入,[[1,2,3],[4,5,6]]但代码产生[[4,5,6],[4,5,6]. 当我输入其他 m × n 矩阵时,会发生同样的事情,代码生成一个 m × n 矩阵,其行相同。

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)

采纳答案by alecxe

The problem is on the initialization step.

问题出在初始化步骤上。

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

This code actually makes every row of your matrixrefer to the same columnsobject. If any item in any column changes - every other column will change:

这段代码实际上使您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]]

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.

希望有帮助。

回答by Ani

you can accept a 2D list in python this way ...

您可以通过这种方式在python中接受二维列表...

simply

简单地

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


for characters


对于字符

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)

or

或者

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

for numbers

对于数字

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)

where n is no of elements in columns while m is no of elements in a row.

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

In pythonic way, this will create a list of list

以pythonic的方式,这将创建一个列表列表

回答by Arik Pamnani

Apart from the accepted answer, you can also initialise your rows in the following manner - matrix[i] = [0]*n

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

Therefore, the following piece of code will work -

因此,以下代码将起作用-

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)

回答by Milen John Thomas

This code takes number of row and column from user then takes elements and displays as a 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)

回答by Sitabja Pal

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)

input

输入

2 3
1 2 3
4 5 6

output[[1, 2, 3], [4, 5, 6]]

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

回答by Abhishek Yadav

If your matrix is given in row manner like below, where size is s*s here 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*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

then you can use this

那么你可以使用这个

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

your matrix will be 'arr'

你的矩阵将是 'arr'

回答by Deepak Kumar

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)

Input : 1 2 3 4 5 6 7 8 9

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

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

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

回答by Aivar Paalberg

Creating matrix with prepopulated numbers can be done with list comprehension. It may be hard to read but it gets job done:

可以使用列表理解来创建带有预填充数字的矩阵。它可能很难阅读,但它可以完成工作:

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)]

with 2 rows and 3 columns matrix will be [[1, 2, 3], [4, 5, 6]], with 3 rows and 2 columns matrix will be [[1, 2], [3, 4], [5, 6]] etc.

2行3列矩阵为[[1, 2, 3], [4, 5, 6]], 3行2列矩阵为[[1, 2], [3, 4], [ 5, 6]] 等。

回答by kundan pandey

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)

Output:

输出:

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]

Note: this code in case of control.it only control no. Of rows but we can enter any number of column we want i.e row[0]=2so be careful. This is not the code where you can control no of columns.

注意:此代码在控制的情况下。它只控制没有。行,但我们可以输入我们想要的任意数量的列,row[0]=2所以要小心。这不是您可以控制列数的代码。

回答by Max Amiri

m,n=map(int,input().split()) # m - number of rows; n - number of columns;

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

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

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

for i in matrix:print(i)

对于矩阵中的 i:print(i)