2016-03-05 52 views
0

我在代码中遇到了这个熟悉的错误(TypeError:'int'object is not iterable),但无法弄清楚如何解决它。我试图加总市场上所有东西的价值,所以我设置了一个循环,将1只香蕉乘以4美元,然后从股票中减去一根香蕉,移动到下一个项目,并跳过剩余零库存的项目。我希望它继续下去,直到所有物品的库存为零,基本上增加了市场上所有物品的价值。 compute_total_value函数是应该执行此操作的函数,但会弹出错误消息。 以下是错误:复合函数:TypeError:'int'对象不可迭代

Traceback (most recent call last): 
    File "/Users/sasha/PycharmProjects/untitled2/shopping.py", line 62, in <module> 
    total_market_value = compute_total_value(market_items) 
    File "/Users/sasha/PycharmProjects/untitled2/shopping.py", line 49, in compute_total_value 
    while sum(stock[items]) != 0: 
TypeError: 'int' object is not iterable 

这里是我的代码:

# Here is the market 
stock = { 
    "banana": 6, 
    "apple": 0, 
    "orange": 32, 
    "pear": 15 
} 

prices = { 
    "banana": 4, 
    "apple": 2, 
    "orange": 1.5, 
    "pear": 3 
} 


def compute_total_value(food): 
    total = 0 
    for items in food: 
     while sum(stock[items]) != 0:  #error is on this line 
      if stock[items] != 0: 
       total += prices[items] 
       stock[items] -= 1 
      else: 
       continue 
     if sum(stock[items]) == 0: 
      break 
    return total 

market_items = ["banana", "orange", "apple", "pear"] 

total_market_value = compute_total_value(market_items) 

print (total_market_value) 
+0

请编辑此给予正确的格式[MCVE。 – jonrsharpe

+1

@ tony-barbarino请不要添加“谢谢你的帮助!”编辑时。编辑通常应该删除像这样的短语。 – Kenster

+1

你的逻辑对我来说没什么意义,你想要的是当前市场清单的价值,即8.5,或者你想要的是股票中所有东西的价值,那就是81.5? – Copperfield

回答

1

好了,问题是很简单的。函数sum()需要可迭代的元素才能工作;但你有stock[items] ... stock是一个字典和items是一个字符串键;例如stock['banana'],其值是6,它是一个整数,而不是可迭代的。

一种可能的解决方案是:sum(stock.values()),因为stock.values()返回字典中所有值的列表。

但是,您的目标没有必要使用功能sum

在你的代码,该解决方案可以是:

stock = { 
    "banana": 6, 
    "apple": 0, 
    "orange": 32, 
    "pear": 15 
} 

prices = { 
    "banana": 4, 
    "apple": 2, 
    "orange": 1.5, 
    "pear": 3 
} 


def compute_total_value(food): 
    total = 0 
    for items in food: 
     while stock[items] != 0: 
      total += prices[items] 
      stock[items] -= 1 
    return total 

market_items = ["banana", "orange", "apple", "pear"] 

total_market_value = compute_total_value(market_items) 

print (total_market_value)