在对象数组而不是字符串数组上的Python string.join(list)

问题:在对象数组而不是字符串数组上的Python string.join(list)

在Python中,我可以执行以下操作:

>>> list = ['a', 'b', 'c']
>>> ', '.join(list)
'a, b, c'

有对象列表时,有什么简单的方法可以做到这一点?

>>> class Obj:
...     def __str__(self):
...         return 'name'
...
>>> list = [Obj(), Obj(), Obj()]
>>> ', '.join(list)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sequence item 0: expected string, instance found

还是我必须求助于for循环?

In Python, I can do:

>>> list = ['a', 'b', 'c']
>>> ', '.join(list)
'a, b, c'

Is there any easy way to do the same when I have a list of objects?

>>> class Obj:
...     def __str__(self):
...         return 'name'
...
>>> list = [Obj(), Obj(), Obj()]
>>> ', '.join(list)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sequence item 0: expected string, instance found

Or do I have to resort to a for loop?


回答 0

您可以改用列表推导或生成器表达式:

', '.join([str(x) for x in list])  # list comprehension
', '.join(str(x) for x in list)    # generator expression

You could use a list comprehension or a generator expression instead:

', '.join([str(x) for x in list])  # list comprehension
', '.join(str(x) for x in list)    # generator expression

回答 1

内置的字符串构造函数将自动调用obj.__str__

''.join(map(str,list))

The built-in string constructor will automatically call obj.__str__:

''.join(map(str,list))

回答 2

另一个解决方案是重写str类的join运算符。

让我们定义一个新类my_string,如下所示

class my_string(str):
    def join(self, l):
        l_tmp = [str(x) for x in l]
        return super(my_string, self).join(l_tmp)

那你可以做

class Obj:
    def __str__(self):
        return 'name'

list = [Obj(), Obj(), Obj()]
comma = my_string(',')

print comma.join(list)

你得到

name,name,name

顺便说一句,通过使用list作为变量名,您正在重新定义list类(关键字)!最好使用另一个标识符名称。

希望您会发现我的回答有用。

another solution is to override the join operator of the str class.

Let us define a new class my_string as follows

class my_string(str):
    def join(self, l):
        l_tmp = [str(x) for x in l]
        return super(my_string, self).join(l_tmp)

Then you can do

class Obj:
    def __str__(self):
        return 'name'

list = [Obj(), Obj(), Obj()]
comma = my_string(',')

print comma.join(list)

and you get

name,name,name

BTW, by using list as variable name you are redefining the list class (keyword) ! Preferably use another identifier name.

Hope you’ll find my answer useful.


回答 3

我知道这是一个过时的文章,但是我认为遗漏的是重载__repr__,因此__repr__ = __str__,这是标记为重复的问题的可接受答案。

I know this is a super old post, but I think what is missed is overriding __repr__, so that __repr__ = __str__, which is the accepted answer of this question marked duplicate.