def GetSale():#calculates expected sale value and returns info on the stock with highest expected sale value
global Prices
global Exposure
global cprice
global bprice
global risk
global shares
global current_highest_sale
best_stock=' '
for value in Prices.values():
cprice=value[1]
bprice=value[0]
for keys, values in Exposure.items():
risk=values[0]
shares=values[1]
Expected_sale_value=( (cprice - bprice ) - risk * cprice) * shares
print (Expected_sale_value)
if current_highest_sale < Expected_sale_value:
current_highest_sale=Expected_sale_value
best_stock=Exposure[keys]
return best_stock +" has the highest expected sale value"
以上是我目前的代码。但出于某种原因,它似乎在做第一个循环,然后是第二个,然后是第二个,然后是第一个,然后是第二个。在返回第一个for
循环之前,它每次到达第二个循环时似乎都会执行第二个循环。正因为如此,我得到的答案是不正确的。
这个问题有点含糊,但回答标题时,可以同时获得键和值,如下所示:
不过,别介意字典里的钥匙是没有顺序的。此外,如果这两个字典不包含相同数量的键,则上面的代码将失败。
考虑到您的问题,我建议您创建一个生成器表达式,该表达式成对导航两个字典,并使用带自定义键的max来计算要计算的销售价格
expected_sale_price
和相应的库存样本数据
示例代码
这个问题没有很好地定义,而且对于某些词典来说,接受的答案将失败。它依赖于密钥排序,这是不保证的。向字典中添加其他键、删除键,甚至添加键的顺序都会影响排序。
更安全的解决方案是选择一个字典,
d
在本例中,从中获取密钥,然后使用这些密钥访问第二个字典:结果:
这并不比其他答案更复杂,而且对于访问哪些键是明确的。如果字典有不同的键顺序,比如
d2 = {'x': 3, 'b':7, 'c': 3, 'a':9}
,那么仍然会给出一致的结果。相关问题 更多 >
编程相关推荐