Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge multiple iterators to get a new iterator which will iterate over them randomly?

Suppose I have a list of iterators:

iterators = [ iter([2, 3, 4]), iter([7, 9]), iter([-1, -2, -3, -4]) ]

How can I create a new iterator using the above iterators such that at each step it will randomly select one of the iterators present in the list (which are not yet finished) and output the next element from that? It should keep outputting elements until all the iterators have finished.

So, for example, if the new iterator is it_combined, I may get the following output when trying to iterate on it

>>> for it in it_combined:
...     print(it, end=" ")
...
2 7 3 -1 4 -2 -3 -4 9
like image 742
Arun Avatar asked Sep 13 '25 19:09

Arun


1 Answers

You can use random.choice to randomly select an iterator from a list. You then have to make sure to delete this iterator from the list once you've exhausted it.

You can use a generator to implement the merging / sampling of your iterators:

import random

random.seed(42)


def combine_iterators(iterators):
    while iterators:
        it = random.choice(iterators)
        try:
            yield next(it)
        except StopIteration:
            iterators.remove(it)


merged_iterator = combine_iterators(
    [iter([2, 3, 4]), iter([7, 9]), iter([-1, -2, -3, -4])]
)
for x in merged_iterator:
    print(x, end=" ")

Outputs:

-1 2 3 -2 7 4 9 -3 -4
like image 58
tlgs Avatar answered Sep 15 '25 13:09

tlgs