Say that there are two iterators:
def genA():
while True:
yield 1
def genB():
while True:
yield 2
gA = genA()
gB = genB()
According to this SO answer they can be evenly interleaved using the 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)
So next(aa)
will shift the iterator output each time, so a bunch of next
calls will result in 1, 2, 1, 2, 1, 2, 1
- 50%
will come from one iterator, and the other 50%
will come from the other.
I am wondering how we can code it so that x%
will come from one iterator, and (1-x)%
from the other. For example, 75%
from the first iterator, and 25%
from the other.
So several calls to next(combinedIterator)
will result in something like this:
1 1 1 2 1 1 1 2 1 1 1 2
For my purpose, it doesn't matter if the output is strictly ordered like above, or if it is random, with the output determined by probability.