I have a YAML document with sequences like this
---
One:
- a
- b
- c
Two:
- d
- e
Three:
- f
- g
- h
- i
I need to get all possible combinations of the elements taken from each list one at a time, only one element at every instance from the list and all list must be used.
I need to do this is python.
Until now, I can print the YAML file using:
#!/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)
A solution using 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)
Output:
[('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')]