Commit 3147b042 authored by Raymond Hettinger's avatar Raymond Hettinger Committed by GitHub

bpo-31270: Modification of Pr 3200 (#3427)

* bpo-31270: Simplify documentation of itertools.zip_longest

* Use repeat(). Track num_active.
parent 0c72a0c4
...@@ -630,26 +630,25 @@ loops that truncate the stream. ...@@ -630,26 +630,25 @@ loops that truncate the stream.
iterables are of uneven length, missing values are filled-in with *fillvalue*. iterables are of uneven length, missing values are filled-in with *fillvalue*.
Iteration continues until the longest iterable is exhausted. Roughly equivalent to:: Iteration continues until the longest iterable is exhausted. Roughly equivalent to::
class ZipExhausted(Exception): def zip_longest(*args, fillvalue=None):
pass
def zip_longest(*args, **kwds):
# zip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D- # zip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D-
fillvalue = kwds.get('fillvalue') iterators = [iter(it) for it in args]
counter = len(args) - 1 num_active = len(iterators)
def sentinel(): if not num_active:
nonlocal counter return
if not counter: while True:
raise ZipExhausted values = []
counter -= 1 for i, it in enumerate(iterators):
yield fillvalue try:
fillers = repeat(fillvalue) value = next(it)
iterators = [chain(it, sentinel(), fillers) for it in args] except StopIteration:
try: num_active -= 1
while iterators: if not num_active:
yield tuple(map(next, iterators)) return
except ZipExhausted: iterators[i] = repeat(fillvalue)
pass value = fillvalue
values.append(value)
yield tuple(values)
If one of the iterables is potentially infinite, then the :func:`zip_longest` If one of the iterables is potentially infinite, then the :func:`zip_longest`
function should be wrapped with something that limits the number of calls function should be wrapped with something that limits the number of calls
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment