簡體   English   中英

用戶在python中輸入n*n矩陣

[英]taking n*n matrix input by user in python

我開始用python編寫代碼。 當我從用戶那里獲取兩個輸入並且兩個輸入之間有一個空格時,我的代碼就像

 min, p = input().split(" ")  
min=int(min)
p=float(p)

效果很好。 在另一個這樣的問題中,我將一個 *n 矩陣作為用戶輸入,我將其聲明為arr=[[0 for i in range(n)] for j in range(n)]打印 arr 給出了一個很好的矩陣(在 a雖然單行)但我要用用戶輸入替換每個元素“0”,所以我使用嵌套循環作為

for i in range(0,n)
    for j in range(0,n)
       arr[i][j]=input()

這也很好用,但在每個元素后按“輸入”按鈕。 在這個特定問題中,用戶將在空格處輸入一行中的元素,而不是按“輸入”按鈕。 我想知道在這種情況下如何像上面的第一種情況一樣使用 split,記住矩陣是 n*n,我們不知道什么是 n。 我更喜歡避免使用 numpy 作為 Python 的初學者。

你可以這樣做:

rows = int(input("Enter number of rows in the matrix: "))
columns = int(input("Enter number of columns in the matrix: "))
matrix = []
print("Enter the %s x %s matrix: "% (rows, columns))
for i in range(rows):
    matrix.append(list(map(int, input().rstrip().split())))

現在您在控制台中輸入如下值:

Enter number of rows in the matrix: 2
Enter number of columns in the matrix: 2
Enter the 2 x 2 matrix:
1 2
3 4
#Take matrix size as input
n=int(input("Enter the matrix size"))

import numpy as np

#initialise nxn matrix with zeroes
mat=np.zeros((n,n))

#input each row at a time,with each element separated by a space
for i in range(n):
   mat[i]=input().split(" ")
print(mat)  

你可以試試這個簡單的方法(在每個數字后按回車...工作正常)::

m1=[[0,0,0],[0,0,0],[0,0,0]]
for x in range (0,3):
    for y in range (0,3):
        m1[x][y]=input()
print (m1)

嘗試這樣的事情,而不是使用現有列表一個一個地設置矩陣:

# take input from user in one row
nn_matrix = raw_input().split()
total_cells =  len(nn_matrix)
# calculate 'n'
row_cells = int(total_cells**0.5)
# calculate rows
matrix = [nn_matrix[i:i+row_cells] for i in xrange(0, total_cells, row_cells)]

例子:

>>> nn_matrix = raw_input().split()
1 2 3 4 5 6 7 8 9
>>> total_cells =  len(nn_matrix)
>>> row_cells = int(total_cells**0.5)
>>> matrix = [nn_matrix[i:i+row_cells] for i in xrange(0, total_cells, row_cells)]
>>> matrix
[['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]
>>> 
>>> import math
>>> line = ' '.join(map(str, range(4*4))) # Take input from user
'0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15'
>>> items = map(int, line.split()) # convert str to int
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
>>> n = int(math.sqrt(len(items))) # len(items) should be n**2
4
>>> matrix = [ items[i*n:(i+1)*n] for i in range(n) ]
[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15]]

好吧,如果矩陣是 n*n,這意味着在第一個輸入行中,您知道輸入行的數量(不, input()不可能不以按下 Enter 鍵結束)。 所以你需要這樣的東西:

arr = []
arr.append(input().split())
for x in range(len(arr[0]) - 1):
    arr.append(input().split())

我使用range(len(arr[0]) - 1)所以它輸入其余的行(因為矩陣寬度和高度相同並且第一行已經從輸入中讀取)。

我也使用.split()沒有" "作為參數,因為它是默認參數。

試試下面,

r=int(input("enter number of rows"));
c=int(input("enter number of columns"));
mat=[];
for row in range(r):
    a=[]
    for col in range(c):
        a.append(row*col);
    mat.append(a)

print mat;
print("Enter The row and column :")
row,col=map(int,input().split())
matrix = [] 
print("Enter the entries rowwise:") 

# For user input 
for i in range(row):          # for loop for row entries 
a =[] 
for j in range(col):      #  for loop for column entries 
     a.append(int(input())) 
matrix.append(a) 
for i in range(row): 
   for j in range(col): 
      print(matrix[i][j], end = " ") 
print()

n= 10 # n 是矩陣的階數

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

打印(矩陣)

r = int(input("Enret Number of Raws : "))

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)

for i in  range(r):

   for j in range(c):

      print(a[i][j],end=" ")

   print()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM