0

Using itertools and permutation() to get all unique combinations of two lists is easy. For instance, if I had:

['a', 'b']
[1, 2]

I could easily get:

[
  [('a',1),('b',2)],
  [('a',2),('b',1)]
]

However, what I really want is to allow duplicate pairings. Each item in the larger list will be unique, but the number of combinations would be exponential, since the same item in the first list could get assigned to multiple items in the second list. So for the two lists above, I would get:

[
  [('a',1),('a',2)],
  [('a',1),('b',2)],
  [('b',1),('a',2)]
  [('b',1),('b',2)]
]

If I had three items in each of the two lists, I would end up with 27 results. What would be the best approach to this?

Erin
  • 3
  • 1
  • 3
    You are looking for `itertools.product`, not `itertools.permutation` – DeepSpace Mar 22 '21 at 17:37
  • you want the *cartesian product* – juanpa.arrivillaga Mar 22 '21 at 17:41
  • I don't believe it does. If I code: ``` x = [["a", "b", "c"], [1, 2, 3]] import itertools for element in itertools.product(*x): print(element) ``` I get 9 pairs. What I'm really looking for is 27 lists with three elements per list: ``` [('a', 1), ('a', 2), ('a', 3)], [('a', 1), ('a', 2), ('b', 3)], [('a', 1), ('a', 2), ('c', 3)], [('a', 1), ('b', 2), ('a', 3)], [('a', 1), ('b', 2), ('b', 3)], [('a', 1), ('b', 2), ('c', 3)], [('a', 1), ('c', 2), ('a', 3)], ... ``` – Erin Mar 22 '21 at 18:23

2 Answers2

0
>>> from itertools import combinations, product
>>> x = ['a', 'b']
>>> y = [1, 2]
>>> list(combinations(product(x, y), 2))
[(('a', 1), ('a', 2)),
 (('a', 1), ('b', 1)),
 (('a', 1), ('b', 2)),
 (('a', 2), ('b', 1)),
 (('a', 2), ('b', 2)),
 (('b', 1), ('b', 2))]
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
0
list_1 = list(itertools.combinations(list(itertools.product(x,y)),2))
list_2 = [i for i in list_1 if i[0][1] != i[1][1]]

print(list_2)

Output

[(('a', 1), ('a', 2)),
 (('a', 1), ('b', 2)),
 (('a', 2), ('b', 1)),
 (('b', 1), ('b', 2))]
DDaly
  • 474
  • 2
  • 6