【发布时间】:2016-12-28 19:48:09
【问题描述】:
我必须根据单位价格和单位数量计算我的股票的总价值。我在 Python 中有以下代码:
prices = {
"banana" : 4,
"apple" : 2,
"orange" : 1.5,
"pear" : 3,
}
stock = {
"banana" : 6,
"apple" : 0,
"orange" : 32,
"pear" : 15,
}
for key in prices:
print key
print "price: %s" % prices[key]
print "stock: %s" % stock[key]
total = 0
for key in prices:
total = total + prices[key]*stock[key]
print total
我已经尝试通过用以下代码替换最后一个块来将其转换为功能更强大的程序:
def total(x):
if len(x) == 1:
return prices[prices.keys()[0]]*stock[prices.keys()[0]]
else:
return prices[prices.keys()[0]]*stock[prices.keys()[0]] + total(x[1:])
print total(prices)
上面的代码得到这个错误:
Traceback (most recent call last):
File "python", line 30, in <module>
File "python", line 28, in total
TypeError: unhashable type
有人可以将我的代码更正为功能更强大的编程版本吗?
【问题讨论】:
标签: python functional-programming