agnsaft
agnsaft

Reputation: 1891

All possible combinations of a list of a list

I am in desperate need for some algorithm help when combining lists inside lists. Assuming that I have the following data structure:

fields = [  ['a1', 'a2', 'a3'],
            ['b1', 'b2', 'b3'],
            ['c1', 'c2', 'c3'],
            ['d1', 'd2', 'd3']  ]

I am trying to write a generator (Python) that will yield each possible combination of the items so that the following code:

for x in thegenerator(fields):
    print(x)

would give the following output:

['a1', 'b1', 'c1', 'd1']
['a1', 'b1', 'c1', 'd2']
['a1', 'b1', 'c1', 'd3']
['a1', 'b1', 'c2', 'd1']
['a1', 'b1', 'c2', 'd2']
['a1', 'b1', 'c2', 'd3']
...
['a3', 'b3', 'c3', 'd3']

However, my mindset is completely off today so I can not think how I best can iterate the structure to get all the combinations the most clean way using Python. I am sure this has been done before by someone, but after a few searches on google and stack I have given up finding the correct combination of keywords in order to find a suitable algorithm for this problem.

Any ideas what the most clean algorithm to fix this would be?

Upvotes: 1

Views: 594

Answers (2)

John La Rooy
John La Rooy

Reputation: 304473

itertools.product(*fields)

Upvotes: 3

David Z
David Z

Reputation: 131760

Just use itertools.product, it does exactly what you're trying to do. If you're interested in the algorithm, you can always look at the source code.

Upvotes: 10

Related Questions