将矩阵转换为稀疏矩阵的Python程序
给定一个大多数元素为 0 的矩阵,我们需要在Python中将此矩阵转换为稀疏矩阵。
例子:
Input: Matrix:
1 0 0 0
0 2 0 0
0 0 3 0
0 0 0 4
5 0 0 0
Output: Sparse Matrix:
0 0 1
1 1 2
2 2 3
3 3 4
4 0 5
Explanation:
Here the Matrix is represented using a 2D list and the Sparse Matrix is represented in the form Row Column Value
In the Sparse Matrix the first row is 0 1 1
indicates that the value of the Matrix at row 0 and column 1 is 1.
方法:
- 创建一个表示稀疏矩阵列表的空列表。
- 遍历二维矩阵以找到非零元素。
- 如果元素不为零,则创建一个临时空列表。
- 将行值、列值和非零元素本身附加到临时列表中。
- 现在将临时列表附加到稀疏矩阵列表中,以便临时列表充当稀疏矩阵列表的子列表。
- 从矩阵中获取所有非零元素后,显示稀疏矩阵。
上述方法已在以下程序的convertToSparseMatrix()
函数中使用:
# Python program to convert a
# matrix to sparse matrix
# function display a matrix
def displayMatrix(matrix):
for row in matrix:
for element in row:
print(element, end =" ")
print()
# function to convert the matrix
# into a sparse matrix
def convertToSparseMatrix(matrix):
# creating an empty sparse
# matrix list
sparseMatrix =[]
# searching values greater
# than zero
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if matrix[i][j] != 0 :
# creating a temporary
# sublist
temp = []
# appending row value, column
# value and element into the
# sublist
temp.append(i)
temp.append(j)
temp.append(matrix[i][j])
# appending the sublist into
# the sparse matrix list
sparseMatrix.append(temp)
# displaying the sparse matrix
print("\nSparse Matrix: ")
displayMatrix(sparseMatrix)
# Driver's code
# initializing a normal matrix
normalMatrix =[[1, 0, 0, 0],
[0, 2, 0, 0],
[0, 0, 3, 0],
[0, 0, 0, 4],
[5, 0, 0, 0]]
# displaying the matrix
displayMatrix(normalMatrix)
# converting the matrix to sparse
# displayMatrix
convertToSparseMatrix(normalMatrix)
输出:
0 1 0 0
0 0 2 0
0 3 0 0
0 0 5 0
0 0 0 4
Sparse Matrix:
0 0 1
1 1 2
2 2 3
3 3 4
4 0 5