将两个字典(价格,股票)中的值相乘然后相加 [英] Multiplying and then summing values from two dictionaries (prices, stock)

查看:104
本文介绍了将两个字典(价格,股票)中的值相乘然后相加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将每个键的值相乘,然后将所有值加在一起以打印单个数字.我知道这可能超级简单,但我被卡住了

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 }

推荐答案

如果需要个人,可以使用dict理解:

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}

或者直接求和:

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

这篇关于将两个字典(价格,股票)中的值相乘然后相加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆