English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python Basic Tutorial

Python Flow Control

Fonctions en Python

Types de données en Python

Python File Operations

Python Objects and Classes

Python Date and Time

Python advanced knowledge

Python reference manual

Python program implementation of matrix transpose

Python example大全

In this example, you will learn about matrix transpose (by using nested lists to create a matrix).

To understand this example, you should understand the followingPython programmingTopic:

In Python, we can implement a matrix as a nested list (a list within a list). We can consider each element as a row of the matrix.

For example, X = [[1, 2], [4, 5], [3, 6]] will represent a3x2matrix. The first row can be chosen as X[0]. And, the element in the first row and first column can be chosen as X[0][0].

The transpose of a matrix is the interchange of rows and columns. It is represented as X'. The element in the i-th row and j-th column of X will be placed in the j-th row and i-th column of X'. Therefore, if X is3x2matrix, then X' will be2x3matrix.

There are several ways to complete this operation in Python.

Matrix transpose using nested loops

# Program uses nested loops to transpose the matrix
X = [[12,7],
    [4 ,5],
    [3 ,8]]
result = [[0,0,0],
         [0,0,0]]
# iterate through rows
for i in range(len(X)):
   # iterate through columns
   for j in range(len(X[0])):
       result[j][i] = X[i][j]
for r in result:
   print(r)

Output result

[12, 4, 3]]
[7, 5, 8]]

In this program, we use nested for loops to traverse each row and each column. At each point, we put the X[i][j] element into result[j][i].

Matrix transpose using nested list comprehension

''' Program uses list comprehension to transpose the matrix '''
X = [[12,7],
    [4 ,5],
    [3 ,8]]
result = [[X[j][i] for j in range(len(X))] for i in range(len(X[0]))]
for r in result:
   print(r)

The output of this program is the same as the one above. We use nested list comprehensions to traverse each element in the matrix.

Python example大全