2017-11-25 145 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

相关问题