To transpose a matrix in Python, you can use the zip()
function in combination with the *
operator:
main.py53 chars3 lines
Here's an example usage:
main.py172 chars9 lines
In this example, the zip(*matrix)
expression transposes the matrix by unpacking the rows of the original matrix as arguments to zip()
. The zip()
function then creates tuples by pairing corresponding elements from each row. Finally, list()
is used to convert the resulting zip object into a list.
Note that the resulting transposed matrix is a list of tuples. If you prefer to have a list of lists, you can modify the transpose()
function as follows:
main.py70 chars3 lines
With this modification, the output will be:
main.py34 chars2 lines
By transposing a matrix, the rows become columns and the columns become rows.
gistlibby LogSnag