Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python join all combinations of elements within each list

Tags:

python

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

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

The example results:

[[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 combinations but does not preserve selecting only one element from each tuple.

Thanks!

like image 998
user992246 Avatar asked Feb 22 '23 17:02

user992246


1 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')]
like image 58
unutbu Avatar answered Feb 25 '23 15:02

unutbu