[Python-iterators] While we're at it...

Thomas Wouters thomas at xs4all.net
Fri Jun 29 20:12:55 EDT 2001


On Fri, Jun 29, 2001 at 10:40:26PM +0000, Quinn Dunkan wrote:

> Of course, an iterator map would be useful:

> def iter_map(f, seq):
>     for o in seq:
>         yield f(o)

> which would work with an infinite sequence.  It's sort of another way to write
> a lazy list, after all.

Let's make that:

def _getitem(iterator):
    try:
        return iterator.next()
    except StopIteration:
        return None

def map_gen(f, *seqs):
    iterators = map(iter, seqs)
    while 1:
        items = map(_getitem, iterators)
        if f is None:
           yield items
        else:
           yield f(items)

Not *quite* perfect, since it relies on the iterator to stay exhausted after
returning StopIteration once, but that could be considered a feature. It
also never stops, though it should probably stop when all iterators are
exhausted. Fixing those issues is left as an exercise to the reader <wink>

-- 
Thomas Wouters <thomas at xs4all.net>

Hi! I'm a .signature virus! copy me into your .signature file to help me spread!




More information about the Python-list mailing list