遍历包含多个数组的 Yaml 文件 (python)

Iterating through Yaml file with many arrays (python)

提问人:math_guy 提问时间:10/13/2023 最后编辑:math_guy 更新时间:10/13/2023 访问量:45

问:

我有以下yaml文件:

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

我通过加载到 python 中

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

我想要的是编写代码,该代码使用yaml文件中的每个值组合自动调用一些函数,如下所示:

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

我知道我可以使用这样的循环:

for item1 in myfile["points"]:
    for item2 in myfile["calls"]:
        my_function(Tiger, item1, item2)

但是我的 yaml 文件实际上有很多这样的数组,不仅仅是“点”和“调用”,还有一百个其他数组(数组中可能有不同数量的元素,并不完全相同)。所以我想用一些更优雅的方式来做,而不是写一堆嵌套的语句。可能吗?for

python 列表 循环 yaml

评论


答:

1赞 Ömer Sezer 10/13/2023 #1

您可以创建具有产品功能的组合。

产品功能:输入可迭代对象的笛卡尔乘积。等效于嵌套的 for 循环。

示例代码:

import yaml
from itertools import product

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

arrays_to_iterate = [myfile["points"], myfile["calls"]]  

# get all possible combinations
combinations = list(product(*arrays_to_iterate))

# sample function implementation here, now only prints the parameters
def my_function(name, *args):
    print(name, *args)
    
for combination in combinations:
    my_function(myfile["name"], *combination)

YAML 文件 (test.yaml):

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

输出:

enter image description here