我有两个字典:
prices = {"banana": 4,"apple": 2}
stock = {"banana": 6,"apple": 0,}
如何从 1 和 2 字典(4*6+2*0 - 在本例中)中获取组合值的总和?
我有两个字典:
prices = {"banana": 4,"apple": 2}
stock = {"banana": 6,"apple": 0,}
如何从 1 和 2 字典(4*6+2*0 - 在本例中)中获取组合值的总和?
>>> prices = {"banana": 4,"apple": 2}
>>> stock = {"banana": 6,"apple": 0}
>>> {k: prices[k] * stock[k] for k in prices.viewkeys() & stock.viewkeys()}
{'banana': 24, 'apple': 0}
也许比其他解决方案更短更整洁。
>>> prices = {"banana": 4, "apple": 2}
>>> stock = {"banana": 6, "apple": 0}
>>> {key: value * stock.get(key, 0) for key, value in prices.items()}
{'banana': 24, 'apple': 0}
prices.iteritems()
在 Python 2 中使用。
这避免了创建一个新集合,并且在技术上只使用一个字典查找。如果您只想要总和,请使用以下命令:
>>> sum(value * stock.get(key, 0) for key, value in prices.items())
24
不假设密钥是相同的
sum(prices[k] * stock.get(k, 0) for k in prices)
遍历键的交集:
mult = {}
for key in prices.viewkeys() & stock.viewkeys():
mult[key] = prices[key] * stock[key]
这可以简化为 dict 理解:
mult = {key: prices[key] * stock[key] for key in prices.viewkeys() & stock.viewkeys()}
这使用dict.viewkeys()
方法(dict.keys()
在 Python 3 中),其作用类似于set
; 该&
运算符的作用类似于集合上的交集运算符,并为您提供两个字典中都存在的所有键。
要对总库存求和,请使用以下sum()
函数:
total_stock = sum(prices[key] * stock[key] for key in prices.viewkeys() & stock.viewkeys())
演示:
>>> prices = {"banana": 4,"apple": 2}
>>> stock = {"banana": 6,"apple": 0}
>>> {key: prices[key] * stock[key] for key in prices.viewkeys() & stock.viewkeys()}
{'banana': 24, 'apple': 0}
>>> sum(prices[key] * stock[key] for key in prices.viewkeys() & stock.viewkeys())
24
>>> prices = {"banana": 4,"apple": 2}
>>> stock = {"banana": 6,"apple": 0}
>>> sum( prices[k] * stock[k] for k in stock)
24
prices = {"banana": 4,"apple": 2}
stock = {"banana": 6,"apple": 0,}
t=0
for i in prices:
t+=prices[i]*stock[i]
print t