【发布时间】:2017-09-19 02:41:04
【问题描述】:
我正在尝试在名为 matrix 的类中实现 str 方法 我当前的代码是
类矩阵(对象):
def __init__(self): # no modification is needed for this method, but you may modify it if you wish to
'''Create and initialize your class attributes.'''
self._matrix = []
self._rooms = 0
def read_file(self,fp): #fp is a file pointer
'''Build an adjacency matrix that you read from a file fp.'''
rooms = fp.readline()
rooms = int(rooms)
self._matrix= [set() for _ in range(rooms+1)]
for line in fp:
line=line.strip()
item=line.split()
item2=int(item[0])
item3=int(item[1])
self._matrix[item2].add(item3)
self._matrix[item3].add(item2)
return self._matrix
def __str__(self):
'''Return the matrix as a string.'''
s=''
matrix=self._matrix
for n in range(len(matrix)-1):
s=s+"{}:{} ".format(n+1,matrix[n+1])
return s
当前,当我通过 print(Matrix()) 调用 str 方法时,我得到输出: 1:{2} 2:{1, 3} 3:{2, 4} 4:{3, 5} 5:{4, 6} 6:{5}
我要打印的是:
1:2
2:1 3
3:2 4
4:3 5
5:4 6
6:5
有什么建议吗?
【问题讨论】:
标签: python string class methods