python是否具有交织发生器/序列的内置函数? [英] Does python have a built-in function for interleaving generators/sequences?
问题描述
我注意到 itertools
没有(在我看来)有一个函数能够交织来自其他几个可迭代对象的元素(而不是压缩它们): p>
def leaf(* args):return(it.next()for it in cycle(imap(chain,args)))
tuple(leaf(['Johann','Sebastian','Bach'],repeat('')))=> ('Johann','','Sebastian','','Bach','')
(编辑)我问的原因是因为我想避免不必要的zip / flatten事件。
很明显,定义 leaf
很简单,但如果有一个预定义的函数可以做同样的事情,我宁愿使用它,或者使用一个非常清晰的生成器表达式。 在itertools中,还是在其他知名库中,或者合适的惯用表达式中,是否内置了这样一个函数?
编辑2:一个更简洁的定义是可能的(使用功能
包):
from函数导入*
compose_mult = partial(减少,合成)
leaf = compose_mult((partial(imap,next),cycle,partial (imap,chain),lambda * args:args))
itertools roundrobin()食谱将是我的第一选择,尽管在你的确切例子中,它会产生一个无限序列,因为它会以最长的迭代而不是最短的序列来停止。当然,解决这个问题很容易。也许值得检查一下不同的方法吗?
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))
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?
这篇关于python是否具有交织发生器/序列的内置函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!