views:

90

answers:

2

Hi

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?

+7  A: 

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.

David Zaslavsky
Nice one. 5more
InsertNickHere
*ashamed*...no really. I looked at the manual entry for itertools and missed this one apparently. Thanks.
invictus
+1  A: 
itertools.product(*fields)
gnibbler
You are right. Had already looked briefly into itertools.product, but apparently not well enough since I thought the functionality did something a bit different.Thanks!
invictus