如何迭代一个YAML文件,从PYTHON的不同列表中给出所有可能的组合

2024-04-19 16:32:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个YAML文档,上面有这样的序列

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

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

我要做的是python。在

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

^{pr2}$

Tags: 文件实例方法文档元素yaml列表序列
1条回答
网友
1楼 · 发布于 2024-04-19 16:32:23

使用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)

输出:

^{pr2}$

相关问题 更多 >