Generate a cross dimensional 2-d array from given arrays of ranges

Viewed 25

Suppose I have a list of lists like this:

list = [[1, 2, 3],
        [4, 5, 6, 7],
        [3, 4]]

I wish to create a 2-d array like this using the above input in Python:

result = [[1,4,3],[1,4,4],[1,5,3],[1,5,4],[1,6,3],[1,6,4],[1,7,3],[1,7,4],
[2,4,3],[2,4,4],[2,5,3],[2,5,4],[2,6,3],[2,6,4],[2,7,3],[2,7,4],
[3,4,3],[3,4,4],[3,5,3],[3,5,4],[3,6,3],[3,6,4],[3,7,3],[3,7,4]]

This is kind of a truth table.

Note - The length of list can vary (it can contain more lists) and also the length of inner lists can vary.

1 Answers

You can use itertools.product(). l is your original list (avoid using "list" as name, due to the existing built-in data structure in python)

res=[list(i) for i in itertools.product(*l)]

>>> print(res)

[[1, 4, 3], [1, 4, 4], [1, 5, 3], [1, 5, 4], [1, 6, 3], [1, 6, 4], [1, 7, 3], [1, 7, 4], [2, 4, 3], [2, 4, 4], [2, 5, 3], [2, 5, 4], [2, 6, 3], [2, 6, 4], [2, 7, 3], [2, 7, 4], [3, 4, 3], [3, 4, 4], [3, 5, 3], [3, 5, 4], [3, 6, 3], [3, 6, 4], [3, 7, 3], [3, 7, 4]]
Related