在Python中,我可以这样做:
>>> list = ['a', 'b', 'c']
>>> ', '.join(list)
'a, b, c'
Run Code Online (Sandbox Code Playgroud)
当我有一个对象列表时,有没有简单的方法来做同样的事情?
>>> 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
Run Code Online (Sandbox Code Playgroud)
或者我是否必须求助于for循环?
Ada*_*eld 401
您可以使用列表推导或生成器表达式:
', '.join([str(x) for x in list]) # list comprehension
', '.join(str(x) for x in list) # generator expression
Run Code Online (Sandbox Code Playgroud)
Tri*_*ych 91
内置的字符串构造函数会自动调用obj.__str__
:
''.join(map(str,list))
Run Code Online (Sandbox Code Playgroud)