tudou
tudou

Reputation: 525

How to create list from a list of tuples

I have the following code. The input is a list of tuples and the tuple itself can be either a list of tuple,

case 1: input

steps = [
    ('func_a', func_a()),
    ('func_b', func_b()),
    ('func_c', func_c())
]

output:

[
    ('func_a', func_a()),
    ('func_b', func_b()),
    ('func_c', func_c())
]

case 2 input:

steps = [
    ('func_a', func_a()),
    ('func_b', func_b()),
    [('func_c', func_c()), (('func_d', func_d()))]
]

output: two lists

[
    ('func_a', func_a()),
    ('func_b', func_b()),
    ('func_c', func_c())
]

[
    ('func_a', func_a()),
    ('func_b', func_b()),
    ('func_d', func_d())
]

case 3 input:

steps = [
    [('func_a', func_a()),('func_e', func_e())]
    ('func_b', func_b()),
    [('func_c', func_c()), (('func_d', func_d()))]
]

Output, 4 lists

[
    ('func_a', func_a()),
    ('func_b', func_b()),
    ('func_c', func_c())
]

[
    ('func_a', func_a()),
    ('func_b', func_b()),
    ('func_d', func_d())
]

[
    ('func_e', func_e()),
    ('func_b', func_b()),
    ('func_c', func_c())
]


[
    ('func_e', func_e()),
    ('func_b', func_b()),
    ('func_d', func_d())
]

The number of tuples in the list can be varied, for example, the nested list can have N tuples.

How to achieve this? Thanks

Upvotes: 0

Views: 48

Answers (1)

Adam.Er8
Adam.Er8

Reputation: 13413

If your input was in a uniform type (meaning a all list elements were lists of tuples), then it would've been easy using itertools.product, like this:

from itertools import product
from pprint import pprint

steps = [
    [('1', 'A'),('5', 'E')],
    [('2', 'B')], # single tuple still enclosed in list
    [('3', 'C'), (('4', 'D'))]
]

result = list(product(*steps))

pprint(result)

BUT unfortunately, it's not, because the lonely tuples are not put inside a list. So, we need to first transform steps a little bit to bring it to the uniform format, then use the same method:

from itertools import product
from pprint import pprint

steps = [
    [('1', 'A'),('5', 'E')],
    ('2', 'B'), # single tuple is NOT enclosed in list
    [('3', 'C'), (('4', 'D'))]
]

steps = [x if isinstance(x, list) else [x] for x in steps] # enclose single tuples in a list...

result = list(product(*steps))

pprint(result)

Output for both is:

[(('1', 'A'), ('2', 'B'), ('3', 'C')),
 (('1', 'A'), ('2', 'B'), ('4', 'D')),
 (('5', 'E'), ('2', 'B'), ('3', 'C')),
 (('5', 'E'), ('2', 'B'), ('4', 'D'))]

Upvotes: 1

Related Questions