字典中值和键之间的计算

问题描述 投票:0回答:2

我正在尝试在字典值和其各自的键之间执行计算。

dict_cashflows = {0:-10000, 1: 500, 2: 1500, 10: 10000} rate=0.06

例如,我想打折上面字典中的现金流量。使用字典键来折扣值非常重要,因此我不需要在键之间填空。

对于字典中的每一对,计算应该是:

value/((1+rate)**key)

如有任何疑问,请随时提出。提前致谢,

python python-3.x dictionary finance
2个回答
2
投票

您可以只迭代键,也可以迭代两者:

dict_cashflows = {0:-10000, 1: 500, 2: 1500, 10: 10000}
rate=0.06
cashflow = {k : dict_cashflows[k] / (1.+rate)**k for k in dict_cashflows.keys()} #building a new dict from iterating over keys
print(cashflow)
cashflow2 = {k : v / (1.+rate)**k for k,v in dict_cashflows.items()} #building a new dict while iterating on both
print(cashflow2)

0
投票

所以,这就是我发现的方式:

dict_cashflows = {0:-10000, 1: 500, 2: 1500, 10: 10000}

   `def NPV_dict(dictcfs,rate=0.06):
    npv=0.0
    periods=list(dictcfs.keys())
    cfs=list(dictcfs.values())
    for i in range(len(dict_cashflows)):
        calc=cfs[i]/((1+rate)**(periods[i]))
        npv+=calc    
    return npv`
© www.soinside.com 2019 - 2024. All rights reserved.