Home >Backend Development >Python Tutorial >How Can I Efficiently Transpose a 2D Matrix in Python?

How Can I Efficiently Transpose a 2D Matrix in Python?

Susan Sarandon
Susan SarandonOriginal
2024-12-22 06:51:09339browse

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:

  • You are creating a new transposed matrix with the correct height but an incorrect width. It should be [None] * len(anArray) instead of [None] * len(anArray[0]).
  • You are overwriting the values in transposed[t] in each iteration. To create a new column, you need to append the value to the existing list in transposed[t].

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn