You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写for循环测试定期投资金额计算函数的5组测试用例

实现方案

你可以用Python内置的zip()函数将4个参数列表按位置配对,每次循环取出一组测试用例参数传入自定义函数即可,完整代码如下:

import numpy_financial as npf

# 自定义定期投资金额计算函数
def contribution_calculator(target_wealth, rate, duration, periodicity):
    inv_amt = -npf.pmt(rate/100/periodicity, duration*periodicity, 0, target_wealth)
    return inv_amt

# 测试用例参数列表
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]

# for循环遍历所有测试用例
for i, (tw, r, dur, per) in enumerate(zip(target_wealth, rate, duration, periodicity), start=1):
    result = contribution_calculator(tw, r, dur, per)
    # 保留2位小数输出结果,可读性更高
    print(f"第{i}组测试用例结果:每期需投资{round(result, 2)}元")

注意事项

  • zip()会将4个参数列表中相同索引的元素打包成元组,刚好匹配你按顺序排列的5组测试用例
  • enumerate()用来标记测试用例序号,方便你对应参数和输出结果
  • 运行前请确保已安装numpy-financial依赖,未安装可执行命令pip install numpy-financial完成安装

内容的提问来源于stack exchange,提问作者Hidden Angle

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 20:00:00