[英]__str__ Method returning sets vertically Python
我正在嘗試在一個名為matrix的類中實現一個str方法,我當前的代碼是
class Matrix(object):
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
任何建議?
不是直接將集合的字符串表示形式添加到輸出字符串,而是將集合中的每個項目轉換為字符串,並將元素連接到帶有" "
作為分隔符的新字符串。 為每一行添加換行符( "\\n"
)。
s+= "%d: %s\n" % (n+1, " ".join([str(x) for x in matrix[n+1]]))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.