Search code examples
pythonpython-itertools

itertools.product with restrictions


Given the following lists of variables:

greek = ['alpha', 'beta', 'gamma']
numbers = [1, 2, 3]
latin = ['x', 'y']

My baseline choice is ['alpha', 1, 'x']. I'd like to generate the following variations, changing one parameter at a time:

variations = [
        ['beta', 1, 'x'], ['gamma', 1, 'x'],  # Varying greek
        ['alpha', 2, 'x'], ['alpha', 3, 'x'], # Varying numbers
        ['alpha', 1, 'y'],                    # Varying latin
        ]

I can generate the full matrix of all combinations with it.product(), and I can get the desired result in a few lines of code as well.

What is a nice, pythonic way to achieve that? Would be great to generalize that to many sets of parameters.


Solution

  • So you iterate only over one place for each place in arrays:

    greek = ['alpha', 'beta', 'gamma']
    numbers = [1, 2, 3]
    latin = ['x', 'y']
    
    arrays = [greek, numbers, latin]
    
    default = [arr[0] for arr in arrays]
    
    for x, iter_arr in enumerate(arrays):
        #arr = [arr[0] for arr in arrays]
        iter_arr = arrays[x]
        for item in iter_arr[1:]:
            default[x] = item
            print(default)
        default[x] = arrays[x][0]
    

    Can i ask for what purpose its done or does this iteration got a name?