Home  >  Article  >  Backend Development  >  How to Transpose a Matrix in Python Using Zip and the * Operator?

How to Transpose a Matrix in Python Using Zip and the * Operator?

DDD
DDDOriginal
2024-10-19 09:02:30675browse

How to Transpose a Matrix in Python Using Zip and the * Operator?

Transposing a Matrix in Python

Transposing a matrix involves switching the rows and columns, resulting in a new matrix where the jth element in the ith row becomes the ith element in the jth row. For instance, transposing the following 2x3 matrix:

A=[[1, 2, 3],
   [4, 5, 6]]

produces the transposed matrix:

[[1, 4],
[2, 5],
[3, 6]]

Using Zip with *

An efficient way to transpose a matrix in Python is to utilize the zip() function in conjunction with the * operator:

<code class="python">def transpose(matrix):
  return zip(*matrix)</code>

This approach iterates over the columns of the input matrix and produces tuples representing the rows of the transposed matrix. If a list of lists is desired as output, the following can be used:

<code class="python">def transpose(matrix):
  return [list(x) for x in zip(*matrix)]</code>

Alternatively, one can apply the map() function along with the list constructor:

<code class="python">def transpose(matrix):
  return map(list, zip(*matrix))</code>

These methods effectively switch the indices of the input matrix, resulting in a transposed matrix that meets the desired criteria.

The above is the detailed content of How to Transpose a Matrix in Python Using Zip and the * Operator?. 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