在对象数组而不是字符串数组上的Python string.join(list) [英] Python string.join(list) on object array rather than string array

查看:87
本文介绍了在对象数组而不是字符串数组上的Python string.join(list)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,我可以这样做:

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

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

Or do I have to resort to a for loop?

推荐答案

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

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

这篇关于在对象数组而不是字符串数组上的Python string.join(list)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆