【问题标题】:How to input matrix (2D list) in Python?如何在 Python 中输入矩阵(二维列表)?
【发布时间】:2014-05-09 13:54:21
【问题描述】:

我尝试创建此代码来输入 m × n 矩阵。我打算输入[[1,2,3],[4,5,6]],但代码产生[[4,5,6],[4,5,6]。当我输入其他 m x n 矩阵时,也会发生同样的事情,代码会产生一个 m x 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)

【问题讨论】:

标签: python list input matrix


【解决方案1】:

问题出在初始化步骤上。

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]

另见:

希望对您有所帮助。

【讨论】:

    【解决方案2】:

    您可以通过这种方式在 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方式,这将创建一个列表列表

    【讨论】:

      【解决方案3】:

      如果你想输入 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

      【讨论】:

        【解决方案4】:

        如果输入是这样的格式,

        1 2 3
        4 5 6
        7 8 9
        

        可以使用一个衬垫

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

        【讨论】:

          【解决方案5】:

          除了接受的答案之外,您还可以通过以下方式初始化您的行 - 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)
          

          【讨论】:

            【解决方案6】:

            此代码从用户那里获取行数和列数,然后获取元素并显示为矩阵。

            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)
            

            【讨论】:

              【解决方案7】:

              如果您的矩阵以如下所示的行方式给出,这里的大小为 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”

              【讨论】:

                【解决方案8】:

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

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

                for i in matrix:print(i)

                【讨论】:

                • 你能解释一下为什么这应该回答 OP 问题吗?
                【解决方案9】:
                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)
                

                【讨论】:

                  【解决方案10】:

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

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

                  输出:

                  【讨论】:

                    【解决方案11】:

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

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

                    【讨论】:

                      【解决方案12】:
                      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'] ]

                      【讨论】:

                        【解决方案13】:
                        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,所以要小心。这不是您可以控制列数的代码。

                        【讨论】:

                          【解决方案14】:
                          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])
                          

                          完美运行

                          【讨论】:

                            【解决方案15】:
                            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]]

                            【讨论】:

                              【解决方案16】:

                              我使用了 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]])
                              

                              输出

                              【讨论】: