Possible sets of different sub-list items with one element of each sub-list

Viewed 27

I am looking for a way to obtain combinations of single elements of all sub-lists contained in a list without knowing in advance the length of the list and the sub-lists. Let me illustrate what I mean via two examples below. I have two lists (myList1 and myList2) and would like to obtain the two combination sets (setsCombo1 and setsCombo1):

myList1    = [['a'], [1, 2, 3], ['X', 'Y']]
setsCombo1 = [['a', 1, 'X'],
              ['a', 1, 'Y'],
              ['a', 2, 'X'],
              ['a', 2, 'Y'],
              ['a', 3, 'X'],
              ['a', 3, 'Y']]

myList2    = [['a'], [1, 2, 3], ['X', 'Y'], [8, 9]]
setsCombo2 = [['a', 1, 'X', 8],
              ['a', 1, 'X', 9],
              ['a', 1, 'Y', 8],
              ['a', 1, 'Y', 9],
              ['a', 2, 'X', 8],
              ['a', 2, 'X', 9],
              ['a', 2, 'Y', 8],
              ['a', 2, 'Y', 9],
              ['a', 3, 'X', 8],
              ['a', 3, 'X', 9],
              ['a', 3, 'Y', 8],
              ['a', 3, 'Y', 9]]

I looked a bit into itertools but couldn't really find anything quickly that is appropriate...

1 Answers

itertools.product with unpacking * (almost) does that:

>>> from itertools import product

>>> list(product(*myList1))

[('a', 1, 'X'),
 ('a', 1, 'Y'),
 ('a', 2, 'X'),
 ('a', 2, 'Y'),
 ('a', 3, 'X'),
 ('a', 3, 'Y')]

To cast the inner elements to lists, we map:

>>> list(map(list, product(*myList1)))

[['a', 1, 'X'],
 ['a', 1, 'Y'],
 ['a', 2, 'X'],
 ['a', 2, 'Y'],
 ['a', 3, 'X'],
 ['a', 3, 'Y']]
Related