在 TripleNode 类中定义 str 方法,将其属性值以一定的格式拼接成一个字符串,然后返回该字符串。class TripleNode(object): def __init__(self, row=0, column=0, value=0): self.row = row self.column = column self.value = value def add_sparse_matrix(A, B): C = [] i = j = 0 while i < len(A) and j < len(B): if A[i].row < B[j].row: C.append(A[i]) i += 1 elif A[i].row > B[j].row: C.append(B[j]) j += 1 else: if A[i].column < B[j].column: C.append(A[i]) i += 1 elif A[i].column > B[j].column: C.append(B[j]) j += 1 else: C.append(TripleNode(A[i].row, A[i].column, A[i].value + B[j].value)) i += 1 while i < len(A): C.append(A[i]) i += 1 while j < len(B): C.append(B[j]) j += 1 return C A = [TripleNode(0, 0, 1), TripleNode(1, 1, 2)] B = [TripleNode(0, 0, 3), TripleNode(1, 1, 4)] C = list(add_sparse_matrix(A, B)) print(C)
时间: 2024-02-14 10:05:39 浏览: 63
Sure, here's an updated version of the TripleNode class with the __str__ method:
```
class TripleNode(object):
def __init__(self, row=0, column=0, value=0):
self.row = row
self.column = column
self.value = value
def __str__(self):
return "TripleNode(row={}, column={}, value={})".format(self.row, self.column, self.value)
```
This method simply returns a string representation of the TripleNode instance, which includes its row, column, and value attributes.
With this updated class definition, when we run the code provided, the print statement at the end will output a list of TripleNode instances, and each instance will be represented as a string according to the __str__ method we just defined.
阅读全文