2

I had a list of sets. I do not know the length of the list apriori. I wanted to find the Cartesian product of the sets in the list in some code I'm writing.

For example: I have

list_of_sets=[set(['A']),set(['A','B','C']), set('D','E')];

I want to output a cartesian product of these sets, which would be,

('A', 'A', 'E')
('A', 'A', 'D')
('A', 'C', 'E')
('A', 'C', 'D')
('A', 'B', 'E')
('A', 'B', 'D')

If I knew that the list had size 3 in advance, I could use the following code to generate this cartesian product.

for i in itertools.product(list_of_sets[0],list_of_sets[1],list_of_sets[2]):
    print i

Is there an easy way to do this when I do not know the size of the list?

1 Answer 1

3

Use itertools.product(*list_of_sets).

Sign up to request clarification or add additional context in comments.

Comments

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.