我写了下面的代码,先创建一个向量列表,然后创建一个不带零的向量字典。
class SparseVec:
def __init__(self, n):
self.val = [0] * n
self.len = len(self.val)
def __len__(self):
return self.len
def __getitem__(self,*i):
return self.val
def __setitem__(self, i, n):
self.val[i] = n
self.len = max(i, self.len)
print 'self.len = ', self.len
def nonzeros(self):
nonzeroDict = {}
for i in range(len(self.val)):
if self.val[i] != 0:
nonzeroDict[i] = self.val[i]
return 'Sparse Vector{}'.format(nonzeroDict)
def __add__(self, other):
length = self.len
result = SparseVec(length)
if self.len < len(other.val):
length = len(other.val)
result = SparseVec(length)
for i in range(self.len):
result[i] = self.val[i] + other.val[i]
for j in other.val:
if j not in self.val:
result[j] = other.val[j]
return result
def __str__(self):
return '{}'.format(self.val)
if __name__ == '__main__':
a = SparseVec(5)
a[2] = 9.2
a[0] = -1
a[3] = 0
print a
print a.nonzeros()
b = SparseVec(5)
b[1] = 1
print b
print b.nonzeros()
c = a+b
print c
print c.nonzeros()
我如何重写__str__
方法以得到类似这样的结果?
print a
[0] = 2 [1] = 5 etc...
我也想要这个:
for ai, i in a:
print 'a[%d]=%g' % (i, ai)
提供与上面类似的结果,并在列表索引前面加上a:
a[0] = 2 a[1] = 5
答案 0 :(得分:0)
>>> val = [2, 5, 7, 9]
>>> ' '.join('[{}] = {}'.format(index, elem)
... for index, elem in enumerate(val))
'[0] = 2 [1] = 5 [2] = 7 [3] = 9'
在每个元素前面都带有一个“ a”:
>>> ' '.join('a[{}] = {}'.format(index, elem)
... for index, elem in enumerate(val))
'a[0] = 2 a[1] = 5 a[2] = 7 a[3] = 9'