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

Python遍历含多数组的YAML文件,生成参数组合调用函数

问题与解决方案

问题描述

现有如下YAML文件:

name: Tiger
points: [100, 5000]
calls: [1, 10]

通过以下Python代码加载:

with open("myfile.yaml") as f:
    myfile = yaml.safe_load(f)

需要自动生成YAML中所有数组元素的组合,调用自定义函数my_function,示例调用如下:

my_function(Tiger, 100, 1)
my_function(Tiger, 100, 10)
my_function(Tiger, 5000, 1)
my_function(Tiger, 5000, 10)

已知嵌套for循环可以实现,但实际YAML包含上百个元素数量不同的数组,希望用更优雅的方式替代大量嵌套循环。

解决方案

完全可以用itertools.product实现,它能自动生成多个可迭代对象的笛卡尔积,不管有多少个数组都无需编写嵌套循环。

具体实现步骤:

  1. 提取YAML中的固定值(比如name)和所有数组类型的字段
  2. 将所有数组的元素收集为列表,作为itertools.product的参数
  3. 遍历生成的笛卡尔积,结合固定值调用目标函数

示例代码:

import yaml
from itertools import product

def my_function(name, *args):
    # 自定义函数逻辑,这里用打印示例
    print(f"my_function({name}, {', '.join(map(str, args))})")

with open("myfile.yaml") as f:
    myfile = yaml.safe_load(f)

# 提取固定名称
target_name = myfile['name']
# 收集所有数组类型的字段值,保持YAML中的字段顺序
array_values = [value for key, value in myfile.items() if key != 'name' and isinstance(value, list)]

# 生成所有组合并调用函数
for combo in product(*array_values):
    my_function(target_name, *combo)

这段代码的优势:

  • 无需修改核心逻辑,就能适配YAML中新增的任意数量数组字段
  • 自动处理不同长度的数组,生成所有可能的组合
  • 代码简洁易维护,彻底避免多层嵌套for循环的冗余

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 19:02:52