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
循环之前,它似乎每次都进行第二个循环。正因为如此,我得到的答案是不正确的。如何一次迭代两个字典并使用两个值和两个键的结果得到结果
它应该做什么?你有代码结构的方式,第二个循环在第一个循环内部,所以它会为第一个循环的每次循环执行一次第二个循环。 – user2357112
请注意,字典是无序的。一次循环使用两本字典通常没有意义,除非它们具有相同的密钥。 – user2357112
我需要它为第一个循环的每次迭代执行第二次循环,因为这两个字典的长度都是相同的。我需要从它们两个的信息来计算Expected_sale_value。但是由于某种原因,如果我在两个字典中都有多个键/值对,那么数学会做出奇怪的事情,并且不会总是显示出来。 – arisonu123