Lozza
Lozza

Reputation: 75

Create all combinations of lists from a list of lists in python

I have a list: l = [1, (2, 3), (4, 5), 6]

I want to choose 3 items from this list, but only one item can be chosen for each sub list. Using combinations I can achieve:

Result = [[1, (2, 3), (4, 5)], [1, (2, 3), 6], [1, (4, 5), 6]]

However the tuples are not expanded. What is the most Pythonic way to produce a list of all the combinations of items within that list?

Example output:

Result = [[1, 2, 4], [1, 2, 5], [1, 2, 6], [1, 3, 4], [1, 3, 5], [1, 3, 6], [2, 4, 6], [2, 5, 6], [3, 4, 6], [3, 5, 6]]

Upvotes: 2

Views: 107

Answers (1)

DSM
DSM

Reputation: 353509

You could combine combinations with product:

>>> from itertools import combinations, product
>>> seq = [1, (2, 3), (4, 5), 6]
>>> seq = [x if isinstance(x, tuple) else (x,) for x in seq]
>>> [sel for subseq in combinations(seq, 3) for sel in product(*subseq)]
[(1, 2, 4), (1, 2, 5), (1, 3, 4), (1, 3, 5), (1, 2, 6), (1, 3, 6), (1, 4, 6), (1, 5, 6), (2, 4, 6), (2, 5, 6), (3, 4, 6), (3, 5, 6)]

where I've converted seq to be a list of tuples (even if the tuples only have one element) first, because that makes later operations much more natural.

Upvotes: 3

Related Questions