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"
Run Code Online (Sandbox Code Playgroud)
以上是我目前的代码.但由于某种原因,它似乎是在做第一个循环,然后是第二个循环,然后是第二个循环,然后是第一个循环,然后是第二个循环.在返回第一个for循环之前,它似乎每次进入第二个循环.正因为如此,我得到的答案是不正确的.
aIK*_*Kid 44
问题有点模糊,但回答标题,你可以同时得到两个键和值:
>>> d = {'a':5, 'b':6, 'c': 3}
>>> d2 = {'a':6, 'b':7, 'c': 3}
>>> for (k,v), (k2,v2) in zip(d.items(), d2.items()):
print k, v
print k2, v2
a 5
a 6
c 3
c 3
b 6
b 7
Run Code Online (Sandbox Code Playgroud)
use*_*699 10
问题没有明确定义,接受的答案对于某些词典来说是失败的.它依赖于密钥排序,这是不能保证的.将附加键添加到字典,删除键,甚至添加它们的顺序都会影响排序.
更安全的解决方案是选择一个字典,d在这种情况下,从中获取密钥,然后使用它们访问第二个字典:
d = {'a':5, 'b':6, 'c': 3}
d2 = {'a':6, 'b':7, 'c': 3}
[(k, d2[k], v) for k, v in d.items()]
Run Code Online (Sandbox Code Playgroud)
结果:
[('b', 7, 6), ('a', 6, 5), ('c', 3, 3)]
Run Code Online (Sandbox Code Playgroud)
这并不比其他答案复杂,并且明确指出要访问哪些键.如果词典具有不同的键排序,那么d2 = {'x': 3, 'b':7, 'c': 3, 'a':9}仍然给出一致的结果.
| 归档时间: |
|
| 查看次数: |
34003 次 |
| 最近记录: |