diff options
author | Raymond Hettinger <python@rcn.com> | 2011-10-30 22:06:14 (GMT) |
---|---|---|
committer | Raymond Hettinger <python@rcn.com> | 2011-10-30 22:06:14 (GMT) |
commit | 6f45d18c2474097a36bec5a769f30d33cd1b12be (patch) | |
tree | ac46990ea7c3124f758146ad83e8ae300bfe4817 | |
parent | e584457e24606ea1498b66dd94a0ecc9bf4c5dc4 (diff) | |
download | cpython-6f45d18c2474097a36bec5a769f30d33cd1b12be.zip cpython-6f45d18c2474097a36bec5a769f30d33cd1b12be.tar.gz cpython-6f45d18c2474097a36bec5a769f30d33cd1b12be.tar.bz2 |
Improve itertools docs with clearer examples of pure python equivalent code.
-rw-r--r-- | Doc/library/functions.rst | 6 | ||||
-rw-r--r-- | Doc/library/itertools.rst | 23 |
2 files changed, 19 insertions, 10 deletions
diff --git a/Doc/library/functions.rst b/Doc/library/functions.rst index ced3745..e5d4a99 100644 --- a/Doc/library/functions.rst +++ b/Doc/library/functions.rst @@ -1367,10 +1367,10 @@ are always available. They are listed here in alphabetical order. def zip(*iterables): # zip('ABCD', 'xy') --> Ax By sentinel = object() - iterables = [iter(it) for it in iterables] - while iterables: + iterators = [iter(it) for it in iterables] + while iterators: result = [] - for it in iterables: + for it in iterators: elem = next(it, sentinel) if elem is sentinel: return diff --git a/Doc/library/itertools.rst b/Doc/library/itertools.rst index 757823d..28625e8 100644 --- a/Doc/library/itertools.rst +++ b/Doc/library/itertools.rst @@ -557,16 +557,25 @@ loops that truncate the stream. iterables are of uneven length, missing values are filled-in with *fillvalue*. Iteration continues until the longest iterable is exhausted. Equivalent to:: - def zip_longest(*args, fillvalue=None): + class ZipExhausted(Exception): + pass + + def zip_longest(*args, **kwds): # zip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D- - def sentinel(counter = ([fillvalue]*(len(args)-1)).pop): - yield counter() # yields the fillvalue, or raises IndexError + fillvalue = kwds.get('fillvalue') + counter = len(args) - 1 + def sentinel(): + nonlocal counter + if not counter: + raise ZipExhausted + counter -= 1 + yield fillvalue fillers = repeat(fillvalue) - iters = [chain(it, sentinel(), fillers) for it in args] + iterators = [chain(it, sentinel(), fillers) for it in args] try: - for tup in zip(*iters): - yield tup - except IndexError: + while iterators: + yield tuple(map(next, iterators)) + except ZipExhausted: pass If one of the iterables is potentially infinite, then the :func:`zip_longest` |