1

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)
Anthon
  • 69,918
  • 32
  • 186
  • 246
  • [`itertools`](https://docs.python.org/3/library/itertools.html) – Burhan Khalid Apr 24 '18 at 04:44
  • This has nothing to do with YAML, after loading the mapping and sequences from YAML, you have lists as values for a dict, that is just Python. You also should never ever need to use the documented unsafe PyYAML `load()`, there is no excuse for you not using `safe_load()`. – Anthon Apr 24 '18 at 05:03
  • @Anthon Can you point me to a resource where proper reading from yaml is being done and how to loop the values after reading from yaml? – Bhavana Mehta Apr 24 '18 at 05:08
  • The only real documenation (apart from the source) is http://pyyaml.org/wiki/PyYAMLDocumentation. Search there for "not safe" – Anthon Apr 24 '18 at 05:14
  • Possible duplicate of [All combinations of a list of lists](https://stackoverflow.com/questions/798854/all-combinations-of-a-list-of-lists) – Tsyvarev Apr 24 '18 at 10:38

1 Answers1

1

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')]
Ashish Acharya
  • 3,349
  • 1
  • 16
  • 25