Matrix Transpose in Python
In Python, transposing a matrix involves converting rows into columns and vice versa. To achieve this, one approach is to use the built-in zip() function.
Consider the following matrix represented by the 2D array theArray:
theArray = [['a','b','c'],['d','e','f'],['g','h','i']]
To transpose theArray, we utilize zip() as follows:
# Python 2 print(tuple(zip(*theArray))) # Python 3 print(list(zip(*theArray)))
Output:
[('a', 'd', 'g'), ('b', 'e', 'h'), ('c', 'f', 'i')]
The zip() function creates an iterable of tuples, each containing the elements of a column from theArray. By converting the iterable into a tuple or list, we obtain the transposed matrix.
Alternatively, you could implement your own matrix transpose function using nested loops. However, the zip() approach is more concise and efficient for this purpose.
The above is the detailed content of How Do I Transpose a Matrix in Python Using zip()?. For more information, please follow other related articles on the PHP Chinese website!