python中如何遍历字典中的键和值_如何一次遍历两个字典,并使用两个字典中的值和键获得结果...

本文介绍如何在Python中遍历两个字典,同时计算预期销售价格。通过生成器表达式和自定义键的`max`函数,结合价格和曝光率计算最佳销售策略。示例代码提供了一个名为`GetSale`的函数,用于计算最高预期销售价值的股票详情。
摘要由CSDN通过智能技术生成

考虑到您的问题,我建议您创建一个生成器表达式,该表达式成对导航两个字典,并使用带自定义键的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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值