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

时间:2021-11-24 20:30:36

In Python, I can do:

在Python中,我可以这样做:

>>> 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?

或者我需要求助于for循环?

2 个解决方案

#1


311  

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

#2


67  

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

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

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

#1


311  

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

#2


67  

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

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

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