The Practice of Python-22 [Li Gang-21 Days Customs Clearance]: Define the Function of Calculating Matrix Transposition
Method 1: Nested cyclic transposition
- First, create a new list with the same length as the first element of the original matrix.
- Each element of the original matrix is traversed (each element is a list), and then each element is traversed by nested loops, adding the elements in the list to the list elements corresponding to the new list.
matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] def print_matrix (m): for ele in m: for e in ele: print("%2d" % e, end=' ') print('') def transform_matrix (m): # m[0] Several elements represent several columns of the original matrix rt = [[] for i in m[0]] for ele in m: for i in range(len(ele)): # rt[i] represents the first row of the new matrix # ele[i] represents the first column of the current row of the original matrix rt[i].append(ele[i]) return rt print_matrix(matrix) ''' 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 ''' print_matrix(transform_matrix(matrix)) ''' 1 5 9 2 6 10 3 7 11 4 8 12 '''
Method 2: Using zip function transposition
- The purpose of the zip function is to merge multiple sequences: the first element of multiple sequences is merged into the first element, the second element of multiple sequences is merged into the second element,...
- Using Reverse Parameter Collection
matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] def print_matrix (m): for ele in m: for e in ele: print("%2d" % e, end=' ') print('') def transform_matrix (m): # zip([1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]) -> (1, 5, 9), ...... # Reverse parameter collection, which converts multiple lists in the matrix into multiple parameters and passes them to zip return list(zip(*m)) print_matrix(matrix) ''' 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 ''' print_matrix(transform_matrix(matrix)) ''' 1 5 9 2 6 10 3 7 11 4 8 12 '''
Method 3: Using numpy module transposition
- Numpy module provides transpose() function to perform transpose, and the function return value is numpy's built-in type: array:
- Calling the array's tolist() method converts the array into a list list list
matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] def print_matrix (m): for ele in m: for e in ele: print("%2d" % e, end=' ') print('') def transform_matrix (m): import numpy return tolist(numpy.transpose(m)) print_matrix(matrix) ''' 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 ''' print_matrix(transform_matrix(matrix)) ''' 1 5 9 2 6 10 3 7 11 4 8 12 '''