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