2017-11-25 143 views
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 

這裏就是我得到的類型錯誤 - 該程序拒絕加入「價格」變量上面創建的字符串。我應該做同樣的事情的飲料價格也一樣,兩者將被加入到字符串的其餘部分:

回答

4

有兩個問題在這裏:

  1. str.join不會改變字符串(字符串是不可變的),它返回一個新的字符串;和
  2. 它需要輸入一個可迭代的連接在一起的字符串,而不是將單個字符串加在一起。

事實上,food_prices是迭代不要緊,因爲你使用for循環中,price s爲的food_prices的元素,這樣的話你加入列表的一個項目。

可以改寫程序,如:

def create_receipt(self): 
    food_prices = self.__foods 
    food_price_string = '\n'.join(str(price) for price in food_prices) food_price_string += '\n' # (optional) add a new line at the end 
    # ... continue processing food_price_string (or return it)
+0

注:即使一個字符串項是Python中的序列(迭代器)。如果列表項是字符串,則不會有TypeError(儘管問題中的「」.join「用法仍然是錯誤的)。要打印食品價格,每行一個:'print(* food_prices,sep ='\ n')'。手動格式化:'s ='\ n'.join(map(str,food_prices))+'\ n'' – jfs

相關問題