我想为向量编写一个类,并且需要能够将列表中的整数转换为字符串并打印出来。
示例: [1,2.5]->“ <1,2.5>”
这是我的想法,但无法正常工作,我们将不胜感激。
class Vector(list):
def __init__(self,other):
assert len(other)!=0, "Invalid Input!"
for e in other:
assert type(e)==int or type(e)==float, "Invalid Input!"
list.__init__(self,other)
def __str__(self):
s = ''
for x in range (len(self)):
s + = str(self.x)
return s
答案 0 :(得分:4)
使用join函数进行自我组合。
def __str__(self):
return "<%s>" % ", ".join(self)
Join基本上将返回列表内容的字符串,并用逗号和空格分隔。然后,将尖括号放在与之合并的字符串中。
答案 1 :(得分:1)
使用f
-字符串的另一种选择
def __str__(self):
return(f'<{super().__str__()[1:-1]}>')