【问题标题】:How can I write a for loop so that it tests all 5 of my test cases?如何编写一个 for 循环来测试我的所有 5 个测试用例?
【发布时间】:2021-08-14 03:08:47
【问题描述】:

我应该根据目标财富计算出定期投资金额。

这是我的用户定义代码:

def contribution_calculator(target_wealth, rate, duration, periodicity):
    inv_amt = -npf.pmt(rate/100/periodicity, duration*periodicity, 0, target_wealth)
    return inv_amt

这些是我的 5 个测试用例,我已将它们放入各自的列表中。

target_wealth = [1000000, 1000000, 3000000, 3000000, 2000000]

rate = [2.5, 2.5, 0.5, 4.0, 3.0]

duration = [25, 12, 25, 25, 10]

periodicity = [12, 1, 12, 12, 2]

例如,测试用例 1 的值为 1000000、2.5、25、12。

如何编写一个 for 循环来测试所有 5 个给定的测试用例?

【问题讨论】:

  • 你是否也想测试这个组合,例如:2000000, 2.5, 25, 12 ?
  • @balandongiv 是的,请!我想测试我的其他组合,例如 1000000, 2.5, 12, 1 用于测试用例 2,3000000, 0.5, 25, 12 用于测试用例 3。有没有办法我可以做一个 for 循环来测试所有这些使用我的用户定义函数contribution_calculator 的案例?
  • 啊,如果你想测试所有组合,你需要itertools.product而不是zip
  • @sabik 我明白了!非常感谢!

标签: python python-3.x numpy user-defined-functions finance


【解决方案1】:

您可以使用zip() 和元组解包,如下所示:

for tw, r, d, p in zip(target_wealth, rate, duration, periodicity):
    ...

也许重命名列表,以便您可以使用完整的变量名:

for target_wealth, rate, duration, periodicity in zip(target_wealths, rates, durations, periodicities):
    ...

PS:如果要测试所有组合,而不是对应的值,可以使用itertools.product 代替zip

import itertools
for target_wealth, rate, duration, periodicity in itertools.product(target_wealths, rates, durations, periodicities):
    ...

【讨论】:

  • 麻烦拆包:for x in zip(...): contribution_calculator(*x)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-09-25
  • 1970-01-01
  • 2021-10-20
  • 2017-09-06
  • 1970-01-01
  • 2013-02-24
  • 1970-01-01
相关资源
最近更新 更多