Two processing methods of matrix transposition in python

  • 2021-07-22 09:57:19
  • OfStack

Method 1: Use conventional thinking


def transpose(M):
  #  Initialize the transposed matrix 
  result = []
  #  Gets rows and columns before transpose 
  row, col = shape(M)
  #  Loop the column first 
  for i in range(col):
    #  Outer circulating container 
    item = [] 
    #  Loop rows inside column loops 
    for index in range(row):
      item.append(M[index][i])
    result.append(item)
  return result

Thoughts: Matrix transposition is from row to column, column to row

First, define a container for the final matrix First, loop i for columns, and define a temporary array for storing data. In the loop of each column, loop j for rows again, and take the M [j] [i] elements and store them in a temporary array At the end of each column loop, the temporary array is stored in the final array When the column loop is completed, the final array is the transposition of the matrix

Method 2: Unpack with zip


def transpose(M):
  #  Direct use zip Unpack it into a transposed tuple iterator, and then strongly transform it into list Deposit in the final list Medium 
  return [list(row) for row in zip(*M)]

Thoughts:

When zip is unpacked, it returns an iterator that combines multiple iterable objects into a tuple sequence, as follows:


my_zip = list(zip(['a', 'b', 'c'], [1, 2, 3])) 
print(my_zip) # [('a', 1), ('b', 2), ('c', 3)]

The tuple is strongly converted to list in each loop and stored in the total list


Related articles: