为不存在的值返回 0
Returning 0 for a value that doesn't exist
我正在尝试构建一个稀疏矩阵,假设我正在尝试像这样初始化 class:
m = Sparse_Matrix(3,3, (0,0,0),(0,1,10),(0,2,11),(1,0,9),(1,2,8),(2,0,7),(2,1,8))
如果我调用 m.row(0),那将 return 该行中的所有值,因此:
m.row(0) -> (0,10,11)
但是,鉴于稀疏矩阵没有任何值 (1,1),我应该 return 0 用于该索引,我将如何处理?例如,
如果我打电话:
m.row(1) -> (9,0,8)
这是我的代码
def row(self, value:int):
row_list = []
for key in self.list_of_tuples:
print(key)
if value == key[0]:
row_list.append(self.matrix.get((key[0], key[1]),0))
print(row_list)
return tuple(row_list)
在我的代码中,self.matrix 是一个字典,其键是索引的元组,其值是与该键对应的值。例如,我会
{(0,1):10, (0,2):11, (1,0):9, (1,2):8, (2,0):7, (2,1):8}
如果特定索引的值为 0,则我不会将其添加到字典中。
编辑:我不允许为此使用 scipy.sparse。
因为你没有 post 其余的 class,我不知道内部实现细节是什么样的,但是这个怎么样:
class SparseMatrix:
def __init__(self, rows: int, cols: int, *entries):
self.rows = rows
self.cols = cols
self.matrix = dict()
for entry in entries:
self.matrix[(entry[0], entry[1])] = entry[2]
def row(self, row_num: int):
return [self.matrix.get((row_num, i), 0) for i in range(self.cols)]
然后:
>>> m = SparseMatrix(3, 3, (0,0,0), (0,1,10), (0,2,11), (1,0,9), (1,2,8), (2,0,7), (2,1,8))
>>> m.row(0)
[0, 10, 11]
>>> m.row(1)
[9, 0, 8]
我正在尝试构建一个稀疏矩阵,假设我正在尝试像这样初始化 class:
m = Sparse_Matrix(3,3, (0,0,0),(0,1,10),(0,2,11),(1,0,9),(1,2,8),(2,0,7),(2,1,8))
如果我调用 m.row(0),那将 return 该行中的所有值,因此:
m.row(0) -> (0,10,11)
但是,鉴于稀疏矩阵没有任何值 (1,1),我应该 return 0 用于该索引,我将如何处理?例如, 如果我打电话:
m.row(1) -> (9,0,8)
这是我的代码
def row(self, value:int):
row_list = []
for key in self.list_of_tuples:
print(key)
if value == key[0]:
row_list.append(self.matrix.get((key[0], key[1]),0))
print(row_list)
return tuple(row_list)
在我的代码中,self.matrix 是一个字典,其键是索引的元组,其值是与该键对应的值。例如,我会
{(0,1):10, (0,2):11, (1,0):9, (1,2):8, (2,0):7, (2,1):8}
如果特定索引的值为 0,则我不会将其添加到字典中。
编辑:我不允许为此使用 scipy.sparse。
因为你没有 post 其余的 class,我不知道内部实现细节是什么样的,但是这个怎么样:
class SparseMatrix:
def __init__(self, rows: int, cols: int, *entries):
self.rows = rows
self.cols = cols
self.matrix = dict()
for entry in entries:
self.matrix[(entry[0], entry[1])] = entry[2]
def row(self, row_num: int):
return [self.matrix.get((row_num, i), 0) for i in range(self.cols)]
然后:
>>> m = SparseMatrix(3, 3, (0,0,0), (0,1,10), (0,2,11), (1,0,9), (1,2,8), (2,0,7), (2,1,8))
>>> m.row(0)
[0, 10, 11]
>>> m.row(1)
[9, 0, 8]