复合函数:TypeError:'int'对象不可迭代

时间:2016-03-05 21:56:36

标签: python-3.x

我在我的代码中遇到了这个熟悉的错误(TypeError:'int'对象不可迭代),但无法弄清楚如何修复它。我正在尝试将市场上所有东西的价值加起来,所以我设置了一个循环,将1个香蕉乘以$ 4,然后从库存中减去一个香蕉,移到下一个项目,并跳过剩余零库存的项目。我希望它能继续下去,直到所有商品库存为零,基本上会增加市场中所有商品的价值。 compute_total_value函数应该执行此操作,但会弹出错误。 以下是错误:

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)

1 个答案:

答案 0 :(得分: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)