2013-04-18 69 views
3

我需要将每个键的值相乘,然后将所有值相加以打印单个数字。我知道这可能是超级简单,但我卡住乘以两个词典中的值并将其相加

在我心中,我喜欢的东西解决这个问题:

for v in prices: 
total = sum(v * (v in stock)) 
print total 

但这样的事情是不会工作:)

prices = { 
"banana": 4, 
"apple": 2, 
"orange": 1.5, 
"pear": 3 } 

stock = { 
"banana": 6, 
"apple": 0, 
"orange": 32, 
"pear": 15 } 
+0

重复:HTTP:/ /stackoverflow.com/questions/29189978/computing-shopping-list-total-using-dictionaries/29191277,http://stackoverflow.com/questions/19547281/loop-through-2-dictionaries – smci

回答

7

你可以使用字典理解,如果你想要的人:

>>> {k: prices[k]*stock[k] for k in prices} 
{'orange': 48.0, 'pear': 45, 'banana': 24, 'apple': 0} 

,或者直接转到总:

>>> sum(prices[k]*stock[k] for k in prices) 
117.0 
+0

假设'stock'具有与“价格”相同的密钥。也许'stock.get(k,1)'会更合适,但我不确定......如果你只对python3中的重叠感兴趣,可以使用'for prices.keys()&stock .keys()'(python2.7它是keysview我认为) – mgilson

+0

是的,取决于用例。我想也许是股票。get(k,0)',假设默认数字为零,但至少这样你会得到一个很好的'KeyError'并且可以从那里决定。 :^) – DSM

+0

哦,对。 'get(k,0)'比使用1更有意义。毕竟,你无法为没有库存的物品收费。 – mgilson

2

如果你想知道,如何通过词典使用键遍历,指数字典和领悟的字典,这将是一个直截了当

>>> total = {key: price * stock[key] for key, price in prices.items()} 
>>> total 
{'orange': 48.0, 'pear': 45, 'banana': 24, 'apple': 0} 

即使你的Python的实现不提供解释的理解(< PY 2.7),你可以把它作为一个列表理解到dict内置

>>> dict((key, price * stock[key]) for key, price in prices.items()) 
{'orange': 48.0, 'pear': 45, 'banana': 24, 'apple': 0} 

如果你不要;不想2之间兼容.X和3.X你也可以使用iteritems代替 项目

{key: price * stock[key] for key, price in prices.iteritems()} 

如果你想要一个总的结果,可以通过单独的产品来sum

>>> sum(price * stock[key] for key, price in prices.items()) 
117.0 
0

我猜你在codeacademy?如果是的话只是这样做:

total = 0 
for key in prices: 
    prices = 53 
    stock = 10.5 
    total = prices + stock 
print total 

不像什么指示说你将不得不乘以它们,将其添加到总数之前,所有的值加在一起。希望这可以帮助。根据任务描述为codeacademy

-1
total = 0 
for key in prices: 
    print prices[key] * stock[key] 
    total += prices[key] * stock[key] 
print total 
0

正确答案:

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: 
     value = prices[key] * stock[key] 
     print value 
     total = total + value 
    print total 
0

我写了下面的代码和它的工作。 用于价格键:

print key 
    print "price: %s" % + prices[key] 
    print "stock: %s" % + stock[key] 

在价格键: 值=价格[键] *股票[键] 打印值 总=总+值 打印总

+1

欢迎来到这里:)最好给你发布的代码添加一个解释,作为答案,这样可以帮助访问者理解为什么这是一个很好的答案。 – abarisone