python - 使用类将整数列出为字符串

标签 python list class

我想为向量编写一个类,并且我需要能够将列表中的整数转换为字符串并打印它们。

示例: [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

最佳答案

使用 join 函数将自身组合起来。

def __str__(self):
    return "<%s>" % ", ".join(self)

Join 基本上会返回一个由逗号和空格分隔的列表内容的字符串。然后,我们将尖括号放入与之组合的字符串中。

关于python - 使用类将整数列出为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55775842/

相关文章:

python - 大量在线对话文本的情感分析

python - 由列表推导式形成的矩阵和乘以列表元素之间的区别?

python - 为什么此 python 代码中的内存使用量增加?

python - 过滤列表中的最新项目

list - lisp 中列表元素的两个元素组合(没有重复项)

c# - 通过其变量之一从列表 <generic> 中选择特定项目

Javascript:如何获取每个 ClassName 的项目

python - 为什么类 __dict__ 是映射代理?

python - 尝试在虚拟环境中安装 flask 时出错

c# - DTO/POCO 是否应该在所有属性上都有构造函数和私有(private) setter ?