簡體   English   中英

如何使 output 成為矩陣 Python

[英]How to make the output be a matrix Python

如何使 output 成為矩陣,而不是普通數字? 在此處輸入圖像描述

在每行的開頭和結尾添加方括號的選項不適合

rows = int(input("Rows: "))
columns = int(input("Columns: "))
number = columns
matrix = []
for i in range(rows):
    row = input().split()
    for i in range(len(row)):
        row[i] = int(row[i])
    matrix.append(row)
if rows != columns:
    for i in range(abs(rows-columns)):
        if rows > columns:
            for j in range(rows):
                matrix[j].append("*")
        elif rows < columns:
            for j in range(columns-rows):
                matrix.append(["*"] * columns)
            number = columns
            rows = columns
print("Вы ввели: ")#You entered
for i in range(len(matrix)):
    for j in range(len(matrix[i])):
        if matrix[i][j] != "*":
            print(matrix[i][j], end=" ")
    print()
for i in range(number):
    for j in range(i, rows - i - 1):
        original_element = matrix[i][j]
        matrix[i][j] = matrix[rows - 1 - j][i]
        matrix[rows - 1 - j][i] = matrix[rows - 1 - i][rows - 1 - j]
        matrix[rows - 1 - i][rows - 1 - j] = matrix[j][rows - 1 - i]
        matrix[j][rows - 1 - i] = original_element
print("Поворот на 90 градусов: ")#Rotate 90 degrees
for i in range(len(matrix)):
    for j in range(len(matrix[i])):
        if matrix[i][j] != "*":
            print(matrix[i][j], end=" ")
    print()

嘗試這個:

def printMatrix(m):
   for row in m:
      s = str(row)
      # this will remove all the '*' from position 1 to position n-1
      s = s.replace(", '*'", "")
      # removing eventual '*' in position 0
      s = s.replace("['*', ", "[")
      # s can also be ['*']
      s = s.replace("'*'", "")
      if len(s) != 2:
         print(s)

這會產生以下輸出:

>>> m = [[1, 2 ,3], [1, 2, 3], ['*', 1, 2]]
>>> printMatrix(m)
[1, 2, 3]
[1, 2, 3]
>>> m = [[1, 2 ,3], [1, 2, 3], [1, '*', 2]]
>>> printMatrix(m)
[1, 2, 3]
[1, 2, 3]
[1, 2]

>>> m = [[1, 2 ,3], [1, 2, 3], [1, 2, '*']]
>>> printMatrix(m)
[1, 2, 3]
[1, 2, 3]
[1, 2]

>>> m = [[1, 2, 3], [1, 2, 3], ['*', '*', '*']]
>>> printMatrix(m)
[1, 2, 3]
[1, 2, 3]

暫無
暫無

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

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