Python -- generator interspersing value between iterator -- am I doing this correctly? -


i have function made:

def iter_intersperse(iterover, injectitem, startwithiter = true):     item in iterover:         senditem = (item, injectitem) if startwithiter else (injectitem, item)         yield senditem 

to intersperse item between items in generator. it's wxpython addmany calls , want add spacer between each panel in large dictionary (all spacers same size). works, seems overkill i'm trying though small.

i've gone through few options think of -- creating list of spacers same length dictionary of panels , zipping them, seemed more overkill. thought maybe toggle generator set() true or false, etc, couldn't think of how make work. told awhile if ever making function iterates, you're not thinking of itertool it. know cycle it, takes code function above.

for reference, thought make comprehension, addmany takes list of tuples, , have convert list or dict -- seemed overkill.

can think of more elegant way? or, if not, code above efficient be?

i suggest using zip itertools.repeat. simple enough inline (where you'll know order, presumably), if want in function, can too:

def iter_intersperse(iterover, injectitem, startwithiter = true):     if startwithiter:         return zip(iterover, itertools.repeat(injectitem))     return zip(itertools.repeat(injectitem), iterover) 

if you're using python 2, , don't want list zip returns, use itertools.izip instead.

edit: seems want alternation, rather tuples, try generator function instead:

def iter_intersperse(iterover, injectitem, startwithiter=true):     if startwithiter:         try:             yield next(iterover)         except stopiteration:             return      item in iterover:         yield injectitem         yield item 

this doesn't yeild last copy of injectitem @ end if startwithiter true. if want that, add if not startwithiter: yield injectitem @ end of function. consider adding stopwithiter parameter too, if choice of whether or not want trailing padding value isn't correlated whether or not want leading pad value.

in current , past versions of python, can let stopiteration exception might raised next (if iterator empty) bubble caller. after pep 479 goes effect (in 3.5 , 3.6 if request from __future__ import generator_stop, in 3.7 everyone), however, "leaking" stopiteration transformed runtimeerror. so, avoid issues in future, use try/except pair return generator (which raise new stopiteration exception in outer scope).


Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -