在 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 循环?
最佳答案
您可以改用列表推导式或生成器表达式:
', '.join([str(x) for x in list]) # list comprehension
', '.join(str(x) for x in list) # generator expression
关于Python string.join(list) 对象数组而不是字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/497765/