我无法将两个词典中的数字相乘。这是我的代码:
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:
print "price: %s*%s" % stock[key]*prices[key]
total=total+stock[key]*prices[key]
print total
当我按价格乘以股票时,橙色它应该是1.5 * 32而香蕉它应该是4 * 6但是我在编译此代码时收到错误消息。
答案 0 :(得分:1)
print "price: %s*%s" % stock[key]*prices[key]
需要两个值(每个%s
占位符一个),但只提供一个(乘法结果)。
此外,您需要在乘法附近放置括号,或%
运算符仅适用于stock[key]
:
print "price: %s" % (stock[key]*prices[key])
或更好
print "price: %d" % (stock[key]*prices[key])
答案 1 :(得分:1)
简单错误
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:
print "price: %s*%s" % (stock[key],prices[key])
total=total+stock[key]*prices[key]
print total