0

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?

2
  • This looks like permutations check the itertools library I think. Commented Jan 11, 2022 at 3:46
  • I've tried looking at itertools - product, permutations, combinations; I still can't figure out how to apply them to a nested structure, where order matters. Commented Jan 11, 2022 at 3:52

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.