我想添加每个的库存值并打印出新的总数:
prices = {
"banana" : 4,
"apple" : 2,
"orange" : 1.5,
"pear" : 3,
}
stock = {
"banana" : 6,
"apple" : 0,
"orange" : 32,
"pear" : 15,
}
for key in prices:
total = 0
inventory = (prices[key] * stock[key])
print key
print "inventory value: %s" % (inventory)
total = total + inventory
print total
答案 0 :(得分:1)
您的错误是您在每次迭代时重置total
。
您可以通过使用理解来避免这些错误,这些理解可确保为这类问题提供适当的控制流程:
total = sum(p * stock.get(key,0) for key,p in prices.items())
它比经典循环快得多(并且迭代密钥和项目都可以保存对价格项目的访问权限)并作为最后一个奖励:tf项目没有库存,不会崩溃但会产生0
答案 1 :(得分:1)
将total = 0移出循环
prices = {
"banana" : 4,
"apple" : 2,
"orange" : 1.5,
"pear" : 3,
}
stock = {
"banana" : 6,
"apple" : 0,
"orange" : 32,
"pear" : 15,
}
total = 0
for key in prices:
inventory = (prices[key] * stock[key])
print key
print "inventory value: %s" % (inventory)
total = total + inventory
print total