2017-10-15 69 views
0

我已經寫了一個簡單的函數以及它的輸入,但是我不知道要爲我所需的輸出放入「pass」。這裏是我的代碼:(Python初學者)函數中的矩陣打印

def print_matrix(matrix_in, rows, columns, matrix): 
    pass 

    def print_header(columns): 
     line = "+" 
     for i in range(columns): 
      line += "---+" 
     print(line) 

matrix={(2, 2): 5, (1, 2): 4, (0, 1): 2, (0, 0): 1, (1, 1): 3, (2, 3): 6} 
rows=3 
columns=4 
matrix="Matrix 1" 

print_matrix(matrix, rows, columns, matrix) 

對於這種期望輸出:

Matrix 1 

+---+---+---+---+ 
| 1| 2| 0| 0| 
+---+---+---+---+ 
| 0| 3| 4| 0| 
+---+---+---+---+ 
| 0| 0| 5| 6| 
+---+---+---+---+ 

任何幫助,將不勝感激謝謝。

+0

相關:https://開頭計算器.com/questions/9535954/printing-lists-as-tabular-data –

+0

修復您的縮進請 – harandk

+0

Fi首先,你應該打印矩陣*而不用*行,因爲你需要2個循環 - 外部行,內部列,然後使用'matrix_in.get((row,col),0)'獲取值。 。 –

回答

0

試試這個:

def print_matrix(matrixIn, rows, columns, matrixName): 
    print(matrixName + "\n") 

    for i in range(rows): 
     print("+---" * (rows+1) + "+") 
     for j in range(columns): 
      key = (i,j) 
      value = matrixIn.get(key) 
      if value is None: 
       print("| ", 0, end="") 
      else: 
       print("| ", value, end="") 
     print("|") 
    print("+---" * (rows+1) + "+") 

matrix={(2, 2): 5, (1, 2): 4, (0, 1): 2, (0, 0): 1, (1, 1): 3, (2, 3): 6} 
rows=3 
columns=4 
matrixString="Matrix 1" 

print_matrix(matrix, rows, columns, matrixString) 

結果是:

Matrix 1 

+---+---+---+---+ 
| 1| 2| 0| 0| 
+---+---+---+---+ 
| 0| 3| 4| 0| 
+---+---+---+---+ 
| 0| 0| 5| 6| 
+---+---+---+---+ 
0

不確定字典,用列表,我會做

def print_matrix(matrix): 
    for nr in range(len(matrix[:])): 
     print '+----------------+' 
     print '| '+' | '.join(str(i) for i in matrix[nr][:])+' |' 
    print '+----------------+' 
return 

matrix = [[1,2,0,0],[0,3,4,0],[0,0,5,6]] 
print_matrix(matrix)