On Sun, Sep 20, 2009 at 9:10 AM, kevin parks <k...@mac.com> wrote:
> I am afraid that in the long layoff in python has meant some new constructs
> have passed me by. In googling around I found some nice little code I want
> to use, but i don't quite understand it, how it is called, and what it is an
> example of. I guess there are generators and iterators now and it seems this
> might be an example of one of those new constructs. Can anyone explain what
> it is i am looking at, how it is called, and what it is an example of so
> that I can look it up:
>
> def roundrobin(*iterables):
>    "roundrobin('ABC', 'D', 'EF') --> A D E B F C"
>    # Recipe credited to George Sakkis

The original is here, with an explanation of what it does.

>    pending = len(iterables)
>    nexts = cycle(iter(it).next for it in iterables)

cycle() is part of itertools:
http://docs.python.org/library/itertools.html#itertools.cycle

You can read about iter() and iterators here:
http://docs.python.org/library/functions.html#iter
http://docs.python.org/glossary.html#term-iterator

(iter(it).next for it in iterables) is a generator expression. It
creates an iterator.

The above statement as a whole makes an iterator which will return the
iterators of the arguments in turn, repeatedly.

>    while pending:
>        try:
>            for next in nexts:
>                yield next()

The yield statement makes this into a generator function. It's return
value is a generator - a kind of iterator.

>        except StopIteration:

next() will raise StopIteration when its underlying iterable is exhausted.

>            pending -= 1
>            nexts = cycle(islice(nexts, pending))

This is kind of tricky - it makes a new cycle of iterators that omits
the one that just finished.

I have a writeup of iterators and generators here:
http://personalpages.tds.net/~kent37/kk/00004.html

HTH,
Kent
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to