首页 文章

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

提问于
浏览
231

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

4 回答

  • 1

    另一个解决方案是覆盖str类的join运算符 .

    让我们定义一个新类my_string,如下所示

    class my_string(str):
        def join(self, l):
            l_tmp = [str(x) for x in l]
            return super(my_string, self).join(l_tmp)
    

    那你可以做

    class Obj:
        def __str__(self):
            return 'name'
    
    list = [Obj(), Obj(), Obj()]
    comma = my_string(',')
    
    print comma.join(list)
    

    你明白了

    name,name,name
    

    顺便说一句,通过使用 list 作为变量名,您将重新定义列表类(关键字)!最好使用其他标识符名称 .

    希望你会发现我的答案很有用 .

  • 76

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

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

    我知道这是一个超级老帖子,但我认为错过的是覆盖 __repr__ ,所以 __repr__ = __str__ ,这是question marked duplicate的接受答案 .

  • 346

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

    ''.join(map(str,list))
    

相关问题