简体   繁体   中英

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

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'))]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM