我有一个包含这样序列的 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')]
关于python - 如何迭代 YAML 文件以给出 PYTHON 中不同列表中项目的所有可能组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49993578/