<p>考虑到您的问题,我建议您创建一个生成器表达式,该表达式成对导航两个字典,并使用带自定义键的<a href="http://docs.python.org/2/library/functions.html#max" rel="nofollow">max</a>来计算要计算的销售价格<code>expected_sale_price</code>和相应的库存</p>
<p><em>样本数据</em></p>
<pre><code>Prices = dict(zip(range(10), ((randint(1,100), randint(1,100)) for _ in range(10))))
Exposure = dict(zip(range(10), ((randint(1,100), randint(1,100)) for _ in range(10))))
</code></pre>
<p><em>示例代码</em></p>
<pre><code>def GetSale(Prices, Exposure):
'''Get Sale does not need any globals if you pass the necessary variables as
parameteres
'''
from itertools import izip
def sale_price(args):
'''
Custom Key, used with the max function
'''
key, (bprice, cprice), (risk, shares) = args
return ( (cprice - bprice ) - risk * cprice) * shares
#Generator Function to traverse the dict in pairs
#Each item is of the format (key, (bprice, cprice), (risk, shares))
Price_Exposure = izip(Prices.keys(), Prices.values(), Exposure.values())
#Expected sale price using `max` with custom key
expected_sale_price = max(Price_Exposure, key = sale_price)
key, (bprice, cprice), (risk, shares) = expected_sale_price
#The best stock is the key in the expected_sale_Price
return "Stock {} with values bprice={}, cprice = {}, risk={} and shares={} has the highest expected sale value".format(key, bprice, cprice, risk, shares)
</code></pre>