【问题标题】:Can i join list of classes?我可以加入课程列表吗?
【发布时间】:2012-02-08 00:48:15
【问题描述】:

我需要从具有.__str__() 方法的类列表中获取一个字符串。

所以 potions 是 Potion 类的对象列表。 Potion __str__ 方法只返回药水的名称。 我想过做这样的事情

result = "\n".join(potions)

但只能加入字符串,我不知道如何为加入中的每个类调用__str__()

或者我应该这样做:

for potion in potions:
    result += "{0}\n".format(potion)

或者可能是别的什么?

【问题讨论】:

    标签: python string class join generator


    【解决方案1】:
    result = "\n".join(str(potion) for potion in potions)
    

    也就是说,使用生成器表达式(也可以使用列表推导式——

    result = "\n".join([str(potion) for potion in potions])
    

    potions 中的每个potion 调用str()

    【讨论】:

      【解决方案2】:

      略短的解决方案:

      result = "\n".join(map(str, potions))
      

      【讨论】:

      • map() 据我了解,被认为不如 genexprs/list 理解那么 Pythonic,但是,是的,这也有效。 :)
      猜你喜欢
      • 1970-01-01
      • 2022-01-26
      • 2013-02-25
      • 1970-01-01
      • 1970-01-01
      • 2023-04-10
      • 2021-04-18
      • 1970-01-01
      • 2023-03-19
      相关资源
      最近更新 更多