简体   繁体   English

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

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

I tried to create this code to input an m by n matrix.我尝试创建此代码以输入 m x n 矩阵。 I intended to input [[1,2,3],[4,5,6]] but the code yields [[4,5,6],[4,5,6] .我打算输入[[1,2,3],[4,5,6]]但代码产生[[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 × 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)

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.这段代码实际上使matrix每一行都指向相同的columns对象。 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.希望有帮助。

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的方式,这将创建一个列表列表

If you want to take n lines of input where each line contains m space separated integers like:如果您想输入 n 行,其中每行包含 m 个空格分隔的整数,例如:

1 2 3
4 5 6 
7 8 9 

Then you can use:然后你可以使用:

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

Then print whatever you want like for the above input:然后为上述输入打印您想要的任何内容:

print(a[1][1]) 

O/P would be 5 for 0 based indexing对于基于 0 的索引,O/P 将为 5

If the input is formatted like this,如果输入的格式是这样的,

1 2 3
4 5 6
7 8 9

a one liner can be used可以使用单衬

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

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)

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)

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'

m,n=map(int,input().split()) # m - number of rows; m,n=map(int,input().split()) # m - 行数; n - number of columns; 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)

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)

You can make any dimension of list您可以制作任何维度的列表

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

output:输出:

代码显示与输出

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

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

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]] 等。

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 ie row[0]=2 so be careful.行,但我们可以输入我们想要的任意数量的列,即row[0]=2所以要小心。 This is not the code where you can control no of columns.这不是您可以控制列数的代码。

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

works perfectly完美运行

I used numpy library and it works fine for me.我使用了 numpy 库,它对我来说很好用。 Its just a single line and easy to understand.它只是一行并且易于理解。 The input needs to be in a single size separated by space and the reshape converts the list into shape you want.输入需要是由空格分隔的单一大小,reshape 会将列表转换为您想要的形状。 Here (2,2) resizes the list of 4 elements into 2*2 matrix.这里 (2,2) 将 4 个元素的列表调整为 2*2 矩阵。 Be careful in giving equal number of elements in the input corresponding to the dimension of the matrix.在输入中给出与矩阵维度相对应的相同数量的元素时要小心。

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

print(a)

Input输入

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

Output输出

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM