1

Let's assume I have list a:

a = [0, 0, [0, 1], [0, 1, 2]]

where a can be of any length, and its constituents can be of any length and I want to generate a new list that can be any combination of the values such that for the given example I would return:

b = [[0,0,0,0],
     [0,0,0,1],
     [0,0,0,2], 
     [0,0,1,0],
     [0,0,1,1],
     [0,0,1,2]]

I think it's just a matter of looping, but I would appreciate any help.

Thanks

1 Answer 1

4

Using itertools.product:

>>> import itertools
>>> a = [0, 0, [0, 1], [0, 1, 2]]
>>> a2 = [x if isinstance(x, list) else [x] for x in a]
>>> #  = [[0], [0], [0, 1], [0, 1, 2]]
>>> list(itertools.product(*a2))
[(0, 0, 0, 0), (0, 0, 0, 1), (0, 0, 0, 2), (0, 0, 1, 0), (0, 0, 1, 1), (0, 0, 1, 2)]
Sign up to request clarification or add additional context in comments.

2 Comments

is the # comment intentional?
@MightyPork, Yes, it is. I want to tell that elements should be sequences (not a int).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.