简体   繁体   中英

How to make the output be a matrix Python

How to make the output be a matrix, not ordinary numbers? enter image description here

The option with adding square brackets at the beginning and end of each line is not suitable

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()

Try this:

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)

This produces following outputs:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM