【发布时间】:2020-11-10 07:39:25
【问题描述】:
说有两个迭代器:
def genA():
while True:
yield 1
def genB():
while True:
yield 2
gA = genA()
gB = genB()
根据this SO answer,它们可以使用itertools recipes均匀交错:
def cycle(iterable):
# cycle('ABCD') --> A B C D A B C D A B C D ...
saved = []
for element in iterable:
yield element
saved.append(element)
while saved:
for element in saved:
yield element
def roundrobin(*iterables):
"roundrobin('ABC', 'D', 'EF') --> A D E B F C"
# Recipe credited to George Sakkis
num_active = len(iterables)
nexts = cycle(iter(it).__next__ for it in iterables)
while num_active:
try:
for next in nexts:
yield next()
except StopIteration:
# Remove the iterator we just exhausted from the cycle.
num_active -= 1
nexts = cycle(islice(nexts, num_active))
aa = roundrobin(gA, gB)
next(aa)
所以next(aa) 每次都会移动迭代器输出,所以一堆next 调用将导致1, 2, 1, 2, 1, 2, 1 - 50% 将来自一个迭代器,另一个50% 将来自另一个.
我想知道我们如何对其进行编码,以便x% 来自一个迭代器,而(1-x)% 来自另一个迭代器。例如,75% 来自第一个迭代器,25% 来自另一个迭代器。
所以多次调用next(combinedIterator) 将导致如下结果:
1 1 1 2 1 1 1 2 1 1 1 2
出于我的目的,无论输出是像上面那样严格排序,还是随机的,输出由概率决定。
【问题讨论】: