Andrej
Andrej

Reputation: 3839

Remove particular combinations from itertools.combinations

Suppose we have a pair of tuples where tuples can be of different length. Let's call them tuples t1 and t2:

t1 = ('A', 'B', 'C')
t2 = ('d', 'e')

Now I compute all combinations of length 2 from both tuples using itertools:

import itertools
tuple(itertools.combinations(t1 + t2, 2))

Itertools generator produces all possible combinations, but I need only those which occurs between tuples; the expected output is

(('A', 'd'), ('A', 'e'), ('B', 'd'), ('B', 'e'), ('C', 'd'), ('C', 'e'))

I wonder what is best approach to remove undesired combination.

Upvotes: 2

Views: 684

Answers (1)

Kasravnd
Kasravnd

Reputation: 107297

You need itertools.product :

>>> t1 = ('A', 'B', 'C')
>>> t2 = ('d', 'e')
>>> from itertools import product
>>> 
>>> list(product(t1,t2))
[('A', 'd'), ('A', 'e'), ('B', 'd'), ('B', 'e'), ('C', 'd'), ('C', 'e')]

If you are dealing with short tuples you can simply do this job with a list comprehension :

>>> [(i,j) for i in t1 for j in t2]
[('A', 'd'), ('A', 'e'), ('B', 'd'), ('B', 'e'), ('C', 'd'), ('C', 'e')]

Upvotes: 7

Related Questions