Search code examples
pythonlistpython-itertools

Create all possible 1D lists from 2D list


The idea is that I am creating a decision tree based on N different possible layers. Only certain layers will affect the outcome in some cases, For example: image

In this example, the square can be the outcome of both LL and RL, so this could be represented by "ANY", L.

The problem is that as I can't (to the best of my knowledge) represent "ANY" in python, and the idea is that I will have a dictionary that represents the path to the outcome, i.e.

My_dict = {tuple(["ANY",L]): "Square"}

I have to create an array that looks like the following to represent the possibilities:

[[L,R], L]

I want to be able to go from this list to outputting two lists of the shape:

[L,L], [R,L]

To represent all possible paths that lead to the square.

I feel like this should be doable with the itertools module but I can't find anything myself, itertools.permutations simply returns the positional changes in the list, i.e. [L,[L,R]] and [[L,R],L].

Any suggestions would be great. Keep in mind that the solution needs to work for various data types, i.e. in actuality the tree structure options could be booleans or integers rather than just left or right.


Solution

  • You can use itertools.product:

    from itertools import product
    
    data = [['L','R'], ['L']]
    result = list(product(*data))
    print(result)
    

    [('L', 'L'), ('R', 'L')]