将两个字典的值相乘然后求和 [英] Multiplying and then summing values from two dictionaries
本文介绍了将两个字典的值相乘然后求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要乘以每个键的值,然后将所有值添加到一起打印一个数字。我知道这可能超级简单,但我被困住了
在我看来,我会解决这个问题,例如:
$ b $
total = sum(v *(v in stock))
print total
但是这样的事情不会奏效:)
price = {
banana:4,
apple:2,
orange:1.5,
pear:3}
stock = {
banana:6,
apple:0,
orange:32,
pear b $ b
解决方案
如果您想要个人,可以使用字母理解:
>>> {k:价格[k] * k价格中的k价格}
{'orange':48.0,'pear':45,'banana':24,'apple':0}
或直接转到总计:
>>>总和(价格[k] *股价[k] k价格)
117.0
I need to multiply the values from each key and then add all the values together to print a single number. I know this probably super simple but i'm stuck
In my mind, I'd address this with something like:
for v in prices:
total = sum(v * (v in stock))
print total
But something like that isn't going to work :)
prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3 }
stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15 }
解决方案
You could use a dict comprehension if you wanted the individuals:
>>> {k: prices[k]*stock[k] for k in prices}
{'orange': 48.0, 'pear': 45, 'banana': 24, 'apple': 0}
Or go straight to the total:
>>> sum(prices[k]*stock[k] for k in prices)
117.0
这篇关于将两个字典的值相乘然后求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文