Home >Backend Development >Python Tutorial >How Can I Efficiently Transpose a 2D Matrix in Python?
Matrix Transposition in Python
Matrix transposition involves flipping a matrix's rows and columns to create a new matrix with its original dimensions reversed. Let's consider how to develop a Python function to transpose a 2D matrix.
You provided a Python function, but it does not work correctly. Let's examine your code and identify the errors. In your function:
Here's a corrected version of your function:
def matrixTranspose(anArray): transposed = [[] for _ in range(len(anArray))] for t in range(len(anArray)): for tt in range(len(anArray[t])): transposed[tt].append(anArray[t][tt]) return transposed
Another concise solution exists using Python's built-in zip function, which combines corresponding elements from multiple iterables. It transposes the matrix by creating tuples from the columns and then converting them back to lists:
transposed = list(zip(*anArray))
For Python 3, prefer using the * operator to unpack the tuples and create a list of lists:
transposed = [*zip(*anArray)]
These methods will efficiently transpose a 2D matrix in Python.
The above is the detailed content of How Can I Efficiently Transpose a 2D Matrix in Python?. For more information, please follow other related articles on the PHP Chinese website!