I have m
-length list of tuples.
For example:
m = 2
mylist = [(1, 2), (3, 4)]
I need to get all combinations of these tuples, using only one element from one tuple:
[1, 3]
[1, 4]
[2, 3]
[2, 4]
For m=3
:
mylist = [(1, 2), (3, 4), (5, 6)]
[1, 3, 5]
[1, 3, 6]
[1, 4, 5]
[1, 4, 6]
[2, 3, 5]
[2, 3, 6]
[2, 4, 5]
[2, 4, 6]
Is there any good way to do it for any m
?
You can use itertools.product
:
import itertools
for el in itertools.product(*mylist):
print(el)
Outputs:
(1, 3)
(1, 4)
(2, 3)
(2, 4)
Ref. https://docs.python.org/3/library/itertools.html#itertools.product