2
我有一个类有两个列表作为变量。它有一个对象,它应该将列表中的每个元素添加到(相当长的)字符串中,然后返回到主程序,最终通过打印。我用for循环遍历列表并使用.join()将每个对象添加到字符串,但我得到一个TypeError:“只能加入一个迭代”。“TypeError:只能加入一个迭代”当试图将列表项添加到字符串
列表包含在餐厅购买的东西的价格,所以只是浮动数字。
Class A:
def __init__(self, etc.):
self.__foods = []
self.__drinks = []
然后我有一个对象,它应该打印一张预先确定的收据,然后作为一个字符串传递给主程序。
Class A:
...
def create_receipt(self):
food_price_string = "" # What is eventually joined to the main string
food_prices = self.__foods # What is iterated
for price in food_prices:
food_price_string.join(price) # TypeError here
food_price_string.join("\n") # For the eventual print
这里就是我得到的类型错误 - 该程序拒绝加入“价格”变量上面创建的字符串。我应该做同样的事情的饮料价格也一样,两者将被加入到字符串的其余部分:
注:即使一个字符串项是Python中的序列(迭代器)。如果列表项是字符串,则不会有TypeError(尽管问题中的“”.join“用法仍然是错误的)。要打印食品价格,每行一个:'print(* food_prices,sep ='\ n')'。手动格式化:'s ='\ n'.join(map(str,food_prices))+'\ n'' – jfs