Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I merge two python iterators?

I have two iterators, a list and an itertools.count object (i.e. an infinite value generator). I would like to merge these two into a resulting iterator that will alternate yield values between the two:

>>> import itertools >>> c = itertools.count(1) >>> items = ['foo', 'bar'] >>> merged = imerge(items, c)  # the mythical "imerge" >>> merged.next() 'foo' >>> merged.next() 1 >>> merged.next() 'bar' >>> merged.next() 2 >>> merged.next() Traceback (most recent call last):     ... StopIteration 

What is the simplest, most concise way to do this?

like image 239
David Eyk Avatar asked Oct 28 '08 16:10

David Eyk


People also ask

What does __ ITER __ do in Python?

The __iter__() function returns an iterator for the given object (array, set, tuple, etc. or custom objects). It creates an object that can be accessed one element at a time using __next__() function, which generally comes in handy when dealing with loops.

What is iteration in Python explain ITER () and next method ()?

An iterator is an object that contains a countable number of values. An iterator is an object that can be iterated upon, meaning that you can traverse through all the values. Technically, in Python, an iterator is an object which implements the iterator protocol, which consist of the methods __iter__() and __next__() .

How do I combine two iterators in Java?

If you are given two Iterators in Java, how are you supposed to merge them into one list if both iterators are sorted? The Java's iterator has two important methods you can use: hasNext() and next(). The hasNext() returns a boolean telling if this iterator reaches the end.


1 Answers

A generator will solve your problem nicely.

def imerge(a, b):     for i, j in itertools.izip(a,b):         yield i         yield j 
like image 75
Pramod Avatar answered Sep 28 '22 02:09

Pramod