Sta*_*als 3 python string join class generator
我需要从具有.__str__()方法的类列表中获取一个字符串.
因此,药水是一类药水的对象列表.药水__str__方法只返回药水的名称.我想做这样的事情
result = "\n".join(potions)
Run Code Online (Sandbox Code Playgroud)
但只有字符串可以连接,我不知道如何调用连接__str__()中的每个类.
或者我应该做这样的事情:
for potion in potions:
result += "{0}\n".format(potion)
Run Code Online (Sandbox Code Playgroud)
或者可能是别的什么?
result = "\n".join(str(potion) for potion in potions)
Run Code Online (Sandbox Code Playgroud)
也就是说,使用生成器表达式(也可以使用列表推导 -
result = "\n".join([str(potion) for potion in potions])
Run Code Online (Sandbox Code Playgroud)
打电话str()给每个potion人potions.