本文介绍了在对象数组而不是字符串数组上的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)
发布评论