Given the nested list:
l = [['a','b','c'], ['d'], ['e','f']]
I would like to join them sequentially with '/'.join().
With the expected list result:
['a/d/e', 'a/d/f', 'b/d/e', 'b/d/f', 'c/d/e', 'c/d/f']
The solution needs to be able to scale (2D list of various sizes).
What is the best way to achieve this?
CodePudding user response:
This is what's known as a Cartesian product. Here's an approach using itertools.product:
import itertools as it
list("/".join(p) for p in it.product(*l))
Output:
['a/d/e', 'a/d/f', 'b/d/e', 'b/d/f', 'c/d/e', 'c/d/f']
The itertools.product function takes an arbitrary number of iterables as arguments (and an optional repeat parameter). What I'm doing with *l is unpacking your sublists as separate arguments to the itertools.product function. This is essentially what it sees:
it.product(["a", "b", "c"], ["d"], ["e", "f"])
PS - you could actually use strings as well, since strings are iterable:
In [6]: list(it.product("abc", "d", "ef"))
Out[6]:
[('a', 'd', 'e'),
('a', 'd', 'f'),
('b', 'd', 'e'),
('b', 'd', 'f'),
('c', 'd', 'e'),
('c', 'd', 'f')]
Beware that the size of the Cartesian product of collections A, B, etc is the product of the sizes of each collection. For example, the Cartesian product of (0, 1), ("a", "b", "c") would be 2x3=6. Adding a third collection, (5, 6, 7, 8) bumps the size up to 24.
CodePudding user response:
You need to unpack the sublists and use itertools.product:
from itertools import product
out = ['/'.join(tpl) for tpl in product(*l)]
Output:
['a/d/e', 'a/d/f', 'b/d/e', 'b/d/f', 'c/d/e', 'c/d/f']
