>> for v-6ren">
gpt4 book ai didi

python - 如何在两者之间合并两个生成器?

转载 作者:太空宇宙 更新时间:2023-11-04 07:44:17 24 4
gpt4 key购买 nike

我如何合并两个不同的生成器,在每次迭代中,不同的生成器都会获得 yield ?

>>> gen = merge_generators_in_between("ABCD","12")
>>> for val in gen:
... print val
A
1
B
2
C
D

我怎样才能做到这一点?我没有在 itertools 中找到它的功能.

最佳答案

查看 itertools recipes循环下:

>>> from itertools import cycle, islice
>>> def roundrobin(*iterables):
"roundrobin('ABC', 'D', 'EF') --> A D E B F C"
# Recipe credited to George Sakkis
pending = len(iterables)
nexts = cycle(iter(it).next for it in iterables)
while pending:
try:
for next in nexts:
yield next()
except StopIteration:
pending -= 1
nexts = cycle(islice(nexts, pending))


>>> for x in roundrobin("ABCD", "12"):
print x


A
1
B
2
C
D

关于python - 如何在两者之间合并两个生成器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11539846/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com