How to linearly combine a list of lists in python, where not every item is a list? -


i have list composed of strings , lists:

a = ['a', 'b', 'c', 'd', 'e', ['fgh', 'rst'], 'i',['quv','wxy']] 

how join each element in list of string elements contain 1 of each internal list element, while maintaining position in original list? ex:

targets = ['abcdefghiquv',            'abcdefghiwxy',            'abcderstiquv',            'abcderstiwxy',           ] 

i have attempted in manner below, but, works if last element list

combinations = [] combinations2 = [] s in a:     if isinstance(s, basestring):         combinations.append(s)     else:         seqint = ''.join(combinations)         combinations2.append([seqint])         combinations2.append(s)         combinations[:]=[] comb in list(itertools.product(*combinations2)):     print ''.join(comb) 

using itertools.product surely way go. way (may not totally correct since have never used legacy python much):

# helper function def strtolist(o):     '''takes object , puts in list if it's string'''     if isinstance(o, str):         return [o]     return o  = ['a', 'b', 'c', 'd', 'e', ['fgh', 'rst'], 'i',['quv','wxy']] newa = [strtolist(item) item in a] 

that last step called list comprehension. useful, use of time go read them (there dictionary comprehensions , generator comprehensions).

now have new list looks this:

newa = [['a'], ['b'], ['c'], ['d'], ['e'], ['fgh', 'rst'], ['i'],['quv','wxy']] 

then finish same did before:

from itertools import product  comb in list(product(*newa)):     print ''.join(comb) 

edit: if want gnarly, can of in single statement. don't recommend (not readable):

>>> result = [''.join(combo) combo in product(*[([item] if isinstance(item, basestr) else item) item in a])] >>> assert result == targets # no error: success  

it seems in process of learning i'll make additional comment: unless have reason learning using legacy python (2), suggest switching modern python (current version 3.6). direction headed @ point (though legacy python still around quite while in many contexts).


Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -