简体   繁体   中英

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?

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.

itertools.product(*fields)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM