Nitin Sharma
Nitin Sharma

Reputation: 140

How to do selective combination in Python List?

I'm not really sure how to frame my question, but here's a try. I have a list of strings and tuples of strings. I want all combinations such that I pick only one value from each tuple.

It's much easier to demonstrate with an example.

Input:

x = ['a', ('b', 'c'), ('d', 'e'), 'f']

Output:

y = [
    ['a', 'b', 'd', 'f'],
    ['a', 'c', 'd', 'f'],
    ['a', 'b', 'e', 'f'],
    ['a', 'c', 'e', 'f']
]

Example 2:

Input:

x = ['a', ('b', 'c'), ('d', 'e'), 'f', ('g', 'h')]

Output:

y = [
    ['a', 'b', 'd', 'f', 'g'],
    ['a', 'c', 'd', 'f', 'g'],
    ['a', 'b', 'e', 'f', 'g'],
    ['a', 'c', 'e', 'f', 'g'],
    ['a', 'b', 'd', 'f', 'h'],
    ['a', 'c', 'd', 'f', 'h'],
    ['a', 'b', 'e', 'f', 'h'],
    ['a', 'c', 'e', 'f', 'h']
]

Upvotes: 0

Views: 52

Answers (1)

Ruggero Turra
Ruggero Turra

Reputation: 17680

x = ['a', ('b', 'c'), ('d', 'e'), 'f', ('g', 'h')]

First normalize your input

x = [tuple(xx) for xx in x if not isinstance(x, tuple)]

Then:

import iterools
list(itertools.product(*x))

In the output your have a list of tuples, it should be very easy to get list of list as you want.

Actually the normalization step is not necessary.

Upvotes: 1

Related Questions