2009-01-31 81 views
200

在Python上(名单),我可以这样做:Python中的string.join对象数组,而不是字符串数组

>>> 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循环?

回答

301

你可以用一个列表理解或生成器表达式替代:

', '.join([str(x) for x in list]) # list comprehension 
', '.join(str(x) for x in list) # generator expression 
+1

或发电机表达式:“”。加入(str(x)为列表中的x) – 2009-01-31 00:12:29

+0

对他们哪个更快会有什么想法? – gozzilli 2012-03-23 13:29:33

63

内置的字符串构造函数会自动调用obj.__str__

''.join(map(str,list)) 
相关问题