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

标签 python 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 循环?

最佳答案

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

', '.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/

相关文章:

python - 简单回归示例 pyBrain

python - 如何取消列表中字典中的列表?

python - 不可变容器内的可变类型

list - 稍微改变种子时稍微改变随机列表随机播放的输出

python - 如何在 Python 中压缩两个列表列表?

python - 检查 String 是否是列表中元素的串联

python - 列出两个文件之间比较慢的代码

c# - 如何使用每个 C# 智能技术将项目从其他列表添加到列表中

Java - 将类型列表转换为数组

python - 有条件地停止Python中for循环的迭代