Python combines all combinations of elements in each list

I have a list of tuples, each with two elements: [('1','11'),('2','22'),('3','33'),...n]

How can I find all the combinations of each tuple by only selecting one element of the tuple at a time?

Result:

[[1,2,3], [11,2,3], [11,2,3], [11,22,33], [11,2,33], [11,22,3], [ 1,22,3], [1,22,33], [1,2,33]] `

itertools.combinations gives me all the combinations, but does not save the selection of only one item from each tuple.

Thanks!

+4
source share
2 answers

Use itertools.product :

 In [88]: import itertools as it In [89]: list(it.product(('1','11'),('2','22'),('3','33'))) Out[89]: [('1', '2', '3'), ('1', '2', '33'), ('1', '22', '3'), ('1', '22', '33'), ('11', '2', '3'), ('11', '2', '33'), ('11', '22', '3'), ('11', '22', '33')] 
+7
source

Have you read the itertools documentation?

 >>> import itertools >>> l = [('1','11'),('2','22'),('3','33')] >>> list(itertools.product(*l)) [('1', '2', '3'), ('1', '2', '33'), ('1', '22', '3'), ('1', '22', '33'), ('11', '2', '3'), ('11', '2', '33'), ('11', '22', '3'), ('11', '22', '33')] 
+1
source

All Articles