Processing lists of list in Python

Question:

Have been thinking and attempting with no results how to convert a list of lists into multiple lists.

For instance, the following lists of list:

['RZ', ['backho'], ['forest', 'arb']]

Should be converted to n-lists depending in the maximum length of the elements, so this results in two lists because of length of third element:

['RZ', 'backho', 'forest']
['RZ', 'backho', 'arb']

Each element in the list of lists represents the possibilities to be chosen for the element.

Asked By: John Barton

||

Answers:

You can use itertools.product:

from itertools import product

lst = ['RZ', ['backho'], ['forest', 'arb']]
res = [list(p) for p in product([lst[0]], *lst[1:])]

print(res) # [['RZ', 'backho', 'forest'], ['RZ', 'backho', 'arb']]
Answered By: slider
import itertools
for el in itertools.product(*['RZ', ['backho'], ['forest', 'arb']]):
    print(list(el))

and gives:

['R', 'backho', 'forest']
['R', 'backho', 'arb']
['Z', 'backho', 'forest']
['Z', 'backho', 'arb']

or if you want a list of list:

[list(el) for el in itertools.product(*['RZ', ['backho'], ['forest', 'arb']])]
Answered By: Massifox
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.