考虑到您的问题,我建议您创建一个生成器表达式,该表达式成对导航两个字典,并使用带自定义键的max来计算要计算的销售价格expected_sale_price和相应的库存
样本数据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))))
示例代码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)