Does python have a built-in function for interleaving generators/sequences?

安稳与你 提交于 2019-12-12 09:33:48

问题


I noticed that itertools does not (it seems to me) have a function capable of interleaving elements from several other iterable objects (as opposed to zipping them):

def leaf(*args): return (it.next() for it in cycle(imap(chain,args)))
tuple(leaf(['Johann', 'Sebastian', 'Bach'], repeat(' '))) => ('Johann', ' ', 'Sebastian', ' ', 'Bach', ' ')

(Edit) The reason I ask is because I want to avoid unnecessary zip/flatten occurrences.

Obviously, the definition of leaf is simple enough, but if there is a predefined function that does the same thing, I would prefer to use that, or a very clear generator expression. Is there such a function built-in, in itertools, or in some other well-known library, or a suitable idiomatic expression?

Edit 2: An even more concise definition is possible (using the functional package):

from itertools import *
from functional import *

compose_mult = partial(reduce, compose)
leaf = compose_mult((partial(imap, next), cycle, partial(imap, chain), lambda *args: args))

回答1:


The itertools roundrobin() recipe would've been my first choice, though in your exact example it would produce an infinite sequence, as it stops with the longest iterable, not the shortest. Of course, it would be easy to fix that. Maybe it's worth checking out for a different approach?




回答2:


You're looking for the built-in zip and itertools.chain.from_iterable to flatten the result:

>>> import itertools
>>> list(zip(['Johann', 'Sebastian', 'Bach'], itertools.repeat(' ')))
[('Johann', ' '), ('Sebastian', ' '), ('Bach', ' ')]
>>> list(itertools.chain.from_iterable(_))
['Johann', ' ', 'Sebastian', ' ', 'Bach', ' ']

Note that I used list just to force a nice output. Using the standard itertools, alternative implementations for leaf would be:

leaf = lambda *a: itertools.chain.from_iterable(itertools.izip(*a)) # Python 2.x
leaf = lambda *a: itertools.chain.from_iterable(zip(*a))            # Python 3.x


来源:https://stackoverflow.com/questions/8769829/does-python-have-a-built-in-function-for-interleaving-generators-sequences

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!