List transformation in python -


this question has answer here:

if have list like:

a = ['ab', ['cd', 'de'], 'fg'] 

how transform 2d list shown:

[['ab', 'cd', 'fg'], ['ab', 'de', 'fg']] 

using itertools.product expands 'ab' 'a', 'b'.

you can use itertools.product follows:

>>> list(itertools.product(*(x if isinstance(x, list) else [x] x in a))) [('ab', 'cd', 'fg'), ('ab', 'de', 'fg')] 

here take product, first transform singletons such 'ab' list ['ab'].

if require list of lists output, transform them:

>>> [list(x) x in itertools.product( ...      *(x if isinstance(x, list) else [x] x in a))] [['ab', 'cd', 'fg'], ['ab', 'de', 'fg']] 

Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -