【问题标题】:How to take matrix input from the user and display the matrix in Python?如何从用户那里获取矩阵输入并在 Python 中显示矩阵?
【发布时间】:2018-04-19 03:31:11
【问题描述】:

我有 7 年的 java 和 c++ 经验。我最近开始学习python。有人可以帮助我了解如何读取矩阵的输入并以矩阵格式显示相同的内容。这是我写的代码:

import sys

# no of rows are equal to the number of columns.
n = int(input("Enter the number of rows in a matrix"))
a = [[0 for x in range (n)] for y in range(n)]
for i in range (n):
    for j in range(n):
        a[i][j]=int(input())
        print (a[i][j])
    print("\n")

【问题讨论】:

标签: python python-3.x


【解决方案1】:

如果您使用 pandas,并制作一个数据框...如果您输入 4 作为行数,以及数字 1、2、3、4、5、6、7、8、9、10、11, 12,13,14,15,16...下面的脚本

import pandas as pd
n = int(input("Enter the number of rows in a matrix: "))
a = [[0] * n for i in range(n)]
col_names = []
row_names = []


for i in range(n):
    col_names.append('col ' + str(i+1))
    row_names.append('row ' + str(i+1))  
    for j in range(n):
          a[i][j] = int(input())

print(pd.DataFrame(a,columns = col_names, index = row_names))

...将产生以下输出。

       col 1  col 2  col 3  col 4
row 1      1      2      3      4
row 2      5      6      7      8
row 3      9     10     11     12
row 4     13     14     15     16

另一个选项...使用 numpy... 和第一个选项中的相同值...

import numpy as np
n = int(input("Enter the number of rows in a matrix: "))
a = [[0] * n for i in range(n)]



for i in range(n):
   for j in range(n):
        a[i][j] = int(input())

print(np.matrix(a))

...会产生

[[ 1  2  3  4]
 [ 5  6  7  8]
 [ 9 10 11 12]
 [13 14 15 16]]

【讨论】:

    【解决方案2】:

    这个例子来自我用来计算更大矩阵的程序:

    matrix = []
    rows = int(input("Num rows: "))
    cols = int(input("Num columns: "))
    for r in range(rows):
        row = []
        for c in range(cols):
        row.append(int(input("M1-> R: {} C: {}\n>>>".format(r+1, c+1))))
        matrix.append(row)
    print(matrix)
    

    这也适用于非方阵。 我也使用 Sympy 进行矩阵计算,但这不是重点:)

    【讨论】:

      【解决方案3】:
      print"ENter r and c"
      
      r = int(input("Enter the number of rows in a matrix"))
      
      c = int(input("Enter the number of columns in a matrix"))
      
      a = [[int(input()) for x in range (c)] for y in range(r)]
      

      【讨论】:

        【解决方案4】:
            #program to print matirx by row and column input
        
        a,b = map(int,input("Enter row and column of matrix separated by a space ").split())
        
        # empty list for matrix 
        m=[] 
        
        # taking matrix input
        for i in range(1,a+1):
            l=[]
            for j in range(1,b+1):
                n=int(input(f"Enter a[{i}][{j}] element "))
                l.append(n)
        
            m.append(l)
        
        #printing in matrix form
        for i in range(a):
            for j in range(b):
                if(j==b-1):
                    print(m[i][j], end="")
                else:
                    print(m[i][j], end=" ")
            if i!=a-1:
                print()
        

        【讨论】:

          【解决方案5】:
          import numpy as np
          
          #Taking the number of rows and columns from user
          
          n=int(input("Enter the number of Rows\n"))
          m=int(input("Enter the number of Columns\n"))
          
          """
           You can either use this loop method for below list comprehension;
          
          a=[]
          for i in range(n):
              a.append([0] * m )
          """
          
          #Creating a Empty matrix as as per the instruction of user;
          
          a = [ [0] * m for i in range(n) ]
          
          
          #Taking the element for a matrix from user;
          
          for i in range (n):
              for j in range(m):
                  print("Enter Element No:",i,j)
                  a[i][j] = int(input())
          
          print(np.matrix(a))
          

          【讨论】:

            【解决方案6】:
            r = int(input("Enter Number of Rows : "))
            
            c = int(input("Enter Number of Cols : "))
            
            a = []
            
            for i in range(r):
            
                b = []
            
                for j in range(c):
                    j = int(input("Enter Number in pocket [" + str(i) + "][" + str(j) + "]"))
                    b.append(j)
                a.append(b)
            print("Matrix is ......")
            
            for i in range(r):
            
                for j in range(c):
                    print(a[i][j], end=" ")
            
                print()
            

            【讨论】:

              【解决方案7】:
              r = int(input("Enter the number of rows in a matrix"))
              
              c = int(input("Enter the number of columns in a matrix")) 
              
              a = [list(map(int,input().split())) for _ in range(r)]
              
              for i in a:
                  print(*i)
              

              【讨论】:

                【解决方案8】:
                list = []
                for i in range(3):
                    list.append([])
                    for j in range(3):
                        list[i].append(2)
                   
                for i in range(3):
                    for j in range(3):
                        print(list[i][j],end=" ")
                    print()
                

                【讨论】:

                • 在 StackOverflow 上添加解释为什么你的解决方案应该有效是一种很好的做法。
                猜你喜欢
                • 2014-04-02
                • 1970-01-01
                • 2023-02-04
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多