SoFunction
Updated on 2025-03-01

2 ways to transpose a matrix in python

Method 1: Use conventional ideas

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

Idea: The transposition of a matrix is ​​to turn from a row to a column, and the column to a row

  • First define a container that will eventually store the matrix
  • First loop i on the column and define a temporary array for storing data. In the loop of each column, loop j on the row again, take the M[j][i]th elements into a temporary array
  • After each column loop is completed, save the temporary array into the final array
  • When the column loop is completed, the final array is the matrix transposition

Method 2: Unpacking with zip

def transpose(M):
  # Use zip to unpack iterator directly, and then force it into a list and save it into the final list.  return [list(row) for row in zip(*M)]

Ideas:

After unpacking zip, it returns an iterator that combines multiple iterable objects into a sequence of tuples, as:

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

In each loop, strongly convert the tuple to a list and save it into the total list

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.