Search code examples
pythonpython-3.xnumpypython-itertools

Classified permutations using itertools or numpy


I have a series of dimensions which can take discrete values.

For instance, say I have 4 dimensions each containing a keyword from a dimension-specific list:

color: black, blue, red, green, yellow
size: xs, s, m, l, xl
material: leather, fabric, cotton, wool
gender: male, female

I want to iterate and do some stuff through every possible combination of those dimensions' values.

Is there a way to do this with itertools or numpy assuming two different cases?

  • If each dimension can have only one keyword
  • If each dimension can have one or several keywords

Solution

  • Have you tried itertools.product(*iterables)? Sounds like it's what you're looking for.

    The function takes as many iterables as you want and makes a Cartesian product. Here is an example:

    import itertools
    
    dimension1 = range(3)
    dimension2 = ['a']
    dimension3 = ['hello', 'world']
    
    for res in itertools.product(dimension1, dimension2, dimension3):
        print(*res)
    

    Output:

    0 a hello
    0 a world
    1 a hello
    1 a world
    2 a hello
    2 a world