如何迭代 YAML 文件以给出 PYTHON 中不同列表中项目的所有可能组合

How to iterate a YAML file to give all possible combinations from items in different lists in PYTHON

我有一个包含这样序列的 YAML 文档

---
One: 
 - a
 - b
 - c
Two:
 - d
 - e
Three:
 - f
 - g
 - h 
 - i

我需要从每个列表中一次获取一个元素的所有可能组合,每个列表实例中的一个元素,并且必须使用所有列表。

我需要做的是python。

到目前为止,我可以使用以下方法打印 YAML 文件:

#!/usr/bin/env python

import yaml

with open("parameters.yaml", 'r') as stream:
    try:
        print(yaml.load(stream))
    except yaml.YAMLError as exc:
        print(exc)

使用 itertools 的解决方案:

import itertools
import yaml

with open('parameters.yaml', 'r') as stream:
    try:
        inputdict = yaml.safe_load(stream)
    except yaml.YAMLError as exc:
        print(exc)

total_list = [inputdict[key] for key in inputdict]
combinations = list(itertools.product(*total_list))
print(combinations)

输出:

[('a', 'd', 'f'), ('a', 'd', 'g'), ('a', 'd', 'h'), ('a', 'd', 'i'), ('a', 'e', 'f'), ('a', 'e', 'g'), ('a', 'e', 'h'), ('a', 'e', 'i'), ('b', 'd', 'f'), ('b', 'd', 'g'), ('b', 'd', 'h'), ('b', 'd', 'i'), ('b', 'e', 'f'), ('b', 'e', 'g'), ('b', 'e', 'h'), ('b', 'e', 'i'), ('c', 'd', 'f'), ('c', 'd', 'g'), ('c', 'd', 'h'), ('c', 'd', 'i'), ('c', 'e', 'f'), ('c', 'e', 'g'), ('c', 'e', 'h'), ('c', 'e', 'i')]