-2

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.

John Barton
  • 1,581
  • 4
  • 25
  • 51
  • Do you mean the result should be a cartesian product? – Elisha Oct 08 '19 at 16:58
  • 2
    @schwobaseggl please reopen, this question is not as simple as flattening. – sanyassh Oct 08 '19 at 16:59
  • Would `import itertools; [list(sublist) for sublist in itertools.product(*input)]` do what you want? – Bjartr Oct 08 '19 at 17:00
  • @Bjartr No, it does not, because `RZ` is not inside a `list`. Otherwise, it would. – norok2 Oct 08 '19 at 17:02
  • @JuanPerez Could you perhaps explain a bit more what is the format of the input list? It looks like `'RZ'` and `['backho']` are treated equally. What should happen for e.g. `[0, [1], [2, 3], [4, 5, 6]]`? – norok2 Oct 08 '19 at 17:08

2 Answers2

2

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']]
slider
  • 12,810
  • 1
  • 26
  • 42
  • 1
    or: `res = [list(p) for p in product(*[x if isinstance(x, list) else list(x) for x in lst])]` so that the simple `str` could be anywhere. – norok2 Oct 08 '19 at 17:12
1
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']])]
Massifox
  • 4,369
  • 11
  • 31