File tree 1 file changed +18
-19
lines changed
1 file changed +18
-19
lines changed Original file line number Diff line number Diff line change @@ -630,26 +630,25 @@ loops that truncate the stream.
630
630
iterables are of uneven length, missing values are filled-in with *fillvalue *.
631
631
Iteration continues until the longest iterable is exhausted. Roughly equivalent to::
632
632
633
- class ZipExhausted(Exception):
634
- pass
635
-
636
- def zip_longest(*args, **kwds):
633
+ def zip_longest(*args, fillvalue=None):
637
634
# zip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D-
638
- fillvalue = kwds.get('fillvalue')
639
- counter = len(args) - 1
640
- def sentinel():
641
- nonlocal counter
642
- if not counter:
643
- raise ZipExhausted
644
- counter -= 1
645
- yield fillvalue
646
- fillers = repeat(fillvalue)
647
- iterators = [chain(it, sentinel(), fillers) for it in args]
648
- try:
649
- while iterators:
650
- yield tuple(map(next, iterators))
651
- except ZipExhausted:
652
- pass
635
+ iterators = [iter(it) for it in args]
636
+ num_active = len(iterators)
637
+ if not num_active:
638
+ return
639
+ while True:
640
+ values = []
641
+ for i, it in enumerate(iterators):
642
+ try:
643
+ value = next(it)
644
+ except StopIteration:
645
+ num_active -= 1
646
+ if not num_active:
647
+ return
648
+ iterators[i] = repeat(fillvalue)
649
+ value = fillvalue
650
+ values.append(value)
651
+ yield tuple(values)
653
652
654
653
If one of the iterables is potentially infinite, then the :func: `zip_longest `
655
654
function should be wrapped with something that limits the number of calls
You can’t perform that action at this time.
0 commit comments