1
如何合併兩個不同的生成器,在每次迭代中,一個不同的生成器將獲得收益?如何合併兩臺發電機?
>>> gen = merge_generators_in_between("ABCD","12")
>>> for val in gen:
... print val
A
1
B
2
C
D
我該如何做到這一點?我在itertools
中找不到它的功能。
如何合併兩個不同的生成器,在每次迭代中,一個不同的生成器將獲得收益?如何合併兩臺發電機?
>>> 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