mirror of
https://github.com/python/cpython.git
synced 2025-09-26 18:29:57 +00:00
Merge
This commit is contained in:
commit
5d12faa5b8
2 changed files with 19 additions and 10 deletions
|
@ -1375,10 +1375,10 @@ are always available. They are listed here in alphabetical order.
|
||||||
def zip(*iterables):
|
def zip(*iterables):
|
||||||
# zip('ABCD', 'xy') --> Ax By
|
# zip('ABCD', 'xy') --> Ax By
|
||||||
sentinel = object()
|
sentinel = object()
|
||||||
iterables = [iter(it) for it in iterables]
|
iterators = [iter(it) for it in iterables]
|
||||||
while iterables:
|
while iterators:
|
||||||
result = []
|
result = []
|
||||||
for it in iterables:
|
for it in iterators:
|
||||||
elem = next(it, sentinel)
|
elem = next(it, sentinel)
|
||||||
if elem is sentinel:
|
if elem is sentinel:
|
||||||
return
|
return
|
||||||
|
|
|
@ -595,16 +595,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. Equivalent to::
|
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-
|
# zip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D-
|
||||||
def sentinel(counter = ([fillvalue]*(len(args)-1)).pop):
|
fillvalue = kwds.get('fillvalue')
|
||||||
yield counter() # yields the fillvalue, or raises IndexError
|
counter = len(args) - 1
|
||||||
|
def sentinel():
|
||||||
|
nonlocal counter
|
||||||
|
if not counter:
|
||||||
|
raise ZipExhausted
|
||||||
|
counter -= 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 zip(*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 :func:`zip_longest`
|
If one of the iterables is potentially infinite, then the :func:`zip_longest`
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue