在这里,我有一个程序,通过乘以价格和库存来提供单个杂货的总价。但是我应该用什么来找到所有杂货的总价格?
total = 0
prices = {
"banana" : 4,
"apple" : 2,
"orange" : 1.5,
"pear" : 3
}
stock = {
"banana" : 9,
"apple" : 0,
"orange" : 18,
"pear" : 22
}
for i in prices:
print (i.title())
print ("Price:", prices[i])
print ("Stock:", stock[i])
print ("=================")
for key in prices:
print(key.title() + " Total Price:" , prices[key]*stock[key])
答案 0 :(得分:3)
sum(prices[key] * stock[key] for key in prices)
答案 1 :(得分:1)
假设您的意思是库存中所有商品的总数,您可以将总数据数据存储在以后易于关键的结构中,从而易于操作:
totals = {k:(stock[k] * prices[k]) for k in prices if k in stock}
In [12]: sum(totals.values())
Out[12]: 129.0