Improve itertools docs with clearer examples of pure python equivalent code.
This commit is contained in:
parent
e11a47e207
commit
187aa269c2
|
@ -433,9 +433,9 @@ loops that truncate the stream.
|
||||||
|
|
||||||
def izip(*iterables):
|
def izip(*iterables):
|
||||||
# izip('ABCD', 'xy') --> Ax By
|
# izip('ABCD', 'xy') --> Ax By
|
||||||
iterables = map(iter, iterables)
|
iterators = map(iter, iterables)
|
||||||
while iterables:
|
while iterators:
|
||||||
yield tuple(map(next, iterables))
|
yield tuple(map(next, iterators))
|
||||||
|
|
||||||
.. versionchanged:: 2.4
|
.. versionchanged:: 2.4
|
||||||
When no iterables are specified, returns a zero length iterator instead of
|
When no iterables are specified, returns a zero length iterator instead of
|
||||||
|
@ -456,17 +456,24 @@ 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. Equivalent to::
|
Iteration continues until the longest iterable is exhausted. Equivalent to::
|
||||||
|
|
||||||
|
class ZipExhausted(Exception):
|
||||||
|
pass
|
||||||
|
|
||||||
def izip_longest(*args, **kwds):
|
def izip_longest(*args, **kwds):
|
||||||
# izip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D-
|
# izip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D-
|
||||||
fillvalue = kwds.get('fillvalue')
|
fillvalue = kwds.get('fillvalue')
|
||||||
def sentinel(counter = ([fillvalue]*(len(args)-1)).pop):
|
counter = [len(args) - 1]
|
||||||
yield counter() # yields the fillvalue, or raises IndexError
|
def sentinel():
|
||||||
|
if not counter[0]:
|
||||||
|
raise ZipExhausted
|
||||||
|
counter[0] -= 1
|
||||||
|
yield fillvalue
|
||||||
fillers = repeat(fillvalue)
|
fillers = repeat(fillvalue)
|
||||||
iters = [chain(it, sentinel(), fillers) for it in args]
|
iterators = [chain(it, sentinel(), fillers) for it in args]
|
||||||
try:
|
try:
|
||||||
for tup in izip(*iters):
|
while iterators:
|
||||||
yield tup
|
yield tuple(map(next, iterators))
|
||||||
except IndexError:
|
except ZipExhausted:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
If one of the iterables is potentially infinite, then the
|
If one of the iterables is potentially infinite, then the
|
||||||
|
|
Loading…
Reference in New Issue