我可以合并类的列表吗?

4 投票
2 回答
2554 浏览
提问于 2025-04-17 10:01

我需要从一个包含类的列表中提取出字符串,这些类都有一个叫做 .__str__() 的方法。

这里的potions是一个包含Potion类对象的列表。Potion类的 __str__ 方法会返回药水的名字。

我想过这样做:

result = "\n".join(potions)

但是只有字符串可以被连接,而我不知道怎么在连接的时候调用每个类的 __str__() 方法。

或者我应该这样做:

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

或者可能还有其他的方法?

2 个回答

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

也就是说,使用生成器表达式(其实也可以用列表推导式)来处理。

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

对每一个potionpotions中调用str()函数。

4

稍微简短一点的解决方案:

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

撰写回答