List transformation in python -
this question has answer here:
- get cartesian product of series of lists? 10 answers
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
Post a Comment