@@ -134,7 +134,7 @@ loops that truncate the stream.
134
134
total = func(total, element)
135
135
yield total
136
136
137
- There are a number of uses for the *func * argument. It can be set to
137
+ The *func * argument can be set to
138
138
:func: `min ` for a running minimum, :func: `max ` for a running maximum, or
139
139
:func: `operator.mul ` for a running product. Amortization tables can be
140
140
built by accumulating interest and applying payments:
@@ -181,21 +181,14 @@ loops that truncate the stream.
181
181
>>> unflattened
182
182
[('roses', 'red'), ('violets', 'blue'), ('sugar', 'sweet')]
183
183
184
- >>> for batch in batched(' ABCDEFG' , 3 ):
185
- ... print (batch)
186
- ...
187
- ('A', 'B', 'C')
188
- ('D', 'E', 'F')
189
- ('G',)
190
-
191
184
Roughly equivalent to::
192
185
193
186
def batched(iterable, n):
194
187
# batched('ABCDEFG', 3) → ABC DEF G
195
188
if n < 1:
196
189
raise ValueError('n must be at least one')
197
- it = iter(iterable)
198
- while batch := tuple(islice(it , n)):
190
+ iterable = iter(iterable)
191
+ while batch := tuple(islice(iterable , n)):
199
192
yield batch
200
193
201
194
.. versionadded :: 3.12
@@ -229,13 +222,13 @@ loops that truncate the stream.
229
222
230
223
Return *r * length subsequences of elements from the input *iterable *.
231
224
232
- The combination tuples are emitted in lexicographic ordering according to
225
+ The combination tuples are emitted in lexicographic order according to
233
226
the order of the input *iterable *. So, if the input *iterable * is sorted,
234
227
the output tuples will be produced in sorted order.
235
228
236
229
Elements are treated as unique based on their position, not on their
237
- value. So if the input elements are unique, there will be no repeated
238
- values in each combination.
230
+ value. So, if the input elements are unique, there will be no repeated
231
+ values within each combination.
239
232
240
233
Roughly equivalent to::
241
234
@@ -278,12 +271,12 @@ loops that truncate the stream.
278
271
Return *r * length subsequences of elements from the input *iterable *
279
272
allowing individual elements to be repeated more than once.
280
273
281
- The combination tuples are emitted in lexicographic ordering according to
274
+ The combination tuples are emitted in lexicographic order according to
282
275
the order of the input *iterable *. So, if the input *iterable * is sorted,
283
276
the output tuples will be produced in sorted order.
284
277
285
278
Elements are treated as unique based on their position, not on their
286
- value. So if the input elements are unique, the generated combinations
279
+ value. So, if the input elements are unique, the generated combinations
287
280
will also be unique.
288
281
289
282
Roughly equivalent to::
@@ -324,13 +317,13 @@ loops that truncate the stream.
324
317
.. function :: compress(data, selectors)
325
318
326
319
Make an iterator that filters elements from *data * returning only those that
327
- have a corresponding element in *selectors * that evaluates to `` True `` .
328
- Stops when either the *data * or *selectors * iterables has been exhausted.
320
+ have a corresponding element in *selectors * is true .
321
+ Stops when either the *data * or *selectors * iterables have been exhausted.
329
322
Roughly equivalent to::
330
323
331
324
def compress(data, selectors):
332
325
# compress('ABCDEF', [1,0,1,0,1,1]) → A C E F
333
- return (d for d, s in zip(data, selectors) if s )
326
+ return (datum for datum, selector in zip(data, selectors) if selector )
334
327
335
328
.. versionadded :: 3.1
336
329
@@ -384,7 +377,7 @@ loops that truncate the stream.
384
377
start-up time. Roughly equivalent to::
385
378
386
379
def dropwhile(predicate, iterable):
387
- # dropwhile(lambda x: x<5, [1,4,6,4,1 ]) → 6 4 1
380
+ # dropwhile(lambda x: x<5, [1,4,6,3,8 ]) → 6 3 8
388
381
iterable = iter(iterable)
389
382
for x in iterable:
390
383
if not predicate(x):
@@ -400,7 +393,7 @@ loops that truncate the stream.
400
393
that are false. Roughly equivalent to::
401
394
402
395
def filterfalse(predicate, iterable):
403
- # filterfalse(lambda x: x%2, range(10)) → 0 2 4 6 8
396
+ # filterfalse(lambda x: x<5, [1,4,6,3,8]) → 6 8
404
397
if predicate is None:
405
398
predicate = bool
406
399
for x in iterable:
@@ -436,36 +429,37 @@ loops that truncate the stream.
436
429
437
430
:func: `groupby ` is roughly equivalent to::
438
431
439
- class groupby:
432
+ def groupby(iterable, key=None) :
440
433
# [k for k, g in groupby('AAAABBBCCDAABBB')] → A B C D A B
441
434
# [list(g) for k, g in groupby('AAAABBBCCD')] → AAAA BBB CC D
442
435
443
- def __init__(self, iterable, key=None):
444
- if key is None:
445
- key = lambda x: x
446
- self.keyfunc = key
447
- self.it = iter(iterable)
448
- self.tgtkey = self.currkey = self.currvalue = object()
449
-
450
- def __iter__(self):
451
- return self
452
-
453
- def __next__(self):
454
- self.id = object()
455
- while self.currkey == self.tgtkey:
456
- self.currvalue = next(self.it) # Exit on StopIteration
457
- self.currkey = self.keyfunc(self.currvalue)
458
- self.tgtkey = self.currkey
459
- return (self.currkey, self._grouper(self.tgtkey, self.id))
460
-
461
- def _grouper(self, tgtkey, id):
462
- while self.id is id and self.currkey == tgtkey:
463
- yield self.currvalue
464
- try:
465
- self.currvalue = next(self.it)
466
- except StopIteration:
436
+ keyfunc = (lambda x: x) if key is None else key
437
+ iterator = iter(iterable)
438
+ exhausted = False
439
+
440
+ def _grouper(target_key):
441
+ nonlocal curr_value, curr_key, exhausted
442
+ yield curr_value
443
+ for curr_value in iterator:
444
+ curr_key = keyfunc(curr_value)
445
+ if curr_key != target_key:
467
446
return
468
- self.currkey = self.keyfunc(self.currvalue)
447
+ yield curr_value
448
+ exhausted = True
449
+
450
+ try:
451
+ curr_value = next(iterator)
452
+ except StopIteration:
453
+ return
454
+ curr_key = keyfunc(curr_value)
455
+
456
+ while not exhausted:
457
+ target_key = curr_key
458
+ curr_group = _grouper(target_key)
459
+ yield curr_key, curr_group
460
+ if curr_key == target_key:
461
+ for _ in curr_group:
462
+ pass
469
463
470
464
471
465
.. function :: islice(iterable, stop)
@@ -493,13 +487,15 @@ loops that truncate the stream.
493
487
# islice('ABCDEFG', 2, 4) → C D
494
488
# islice('ABCDEFG', 2, None) → C D E F G
495
489
# islice('ABCDEFG', 0, None, 2) → A C E G
490
+
496
491
s = slice(*args)
497
492
start = 0 if s.start is None else s.start
498
493
stop = s.stop
499
494
step = 1 if s.step is None else s.step
500
495
if start < 0 or (stop is not None and stop < 0) or step <= 0:
501
496
raise ValueError
502
- indices = count() if stop is None else range(max(stop, start))
497
+
498
+ indices = count() if stop is None else range(max(start, stop))
503
499
next_i = start
504
500
for i, element in zip(indices, iterable):
505
501
if i == next_i:
@@ -541,22 +537,25 @@ loops that truncate the stream.
541
537
the output tuples will be produced in sorted order.
542
538
543
539
Elements are treated as unique based on their position, not on their
544
- value. So if the input elements are unique, there will be no repeated
540
+ value. So, if the input elements are unique, there will be no repeated
545
541
values within a permutation.
546
542
547
543
Roughly equivalent to::
548
544
549
545
def permutations(iterable, r=None):
550
546
# permutations('ABCD', 2) → AB AC AD BA BC BD CA CB CD DA DB DC
551
547
# permutations(range(3)) → 012 021 102 120 201 210
548
+
552
549
pool = tuple(iterable)
553
550
n = len(pool)
554
551
r = n if r is None else r
555
552
if r > n:
556
553
return
554
+
557
555
indices = list(range(n))
558
556
cycles = list(range(n, n-r, -1))
559
557
yield tuple(pool[i] for i in indices[:r])
558
+
560
559
while n:
561
560
for i in reversed(range(r)):
562
561
cycles[i] -= 1
@@ -572,7 +571,7 @@ loops that truncate the stream.
572
571
return
573
572
574
573
The code for :func: `permutations ` can be also expressed as a subsequence of
575
- :func: `product `, filtered to exclude entries with repeated elements (those
574
+ :func: `product ` filtered to exclude entries with repeated elements (those
576
575
from the same position in the input pool)::
577
576
578
577
def permutations(iterable, r=None):
@@ -666,17 +665,16 @@ loops that truncate the stream.
666
665
predicate is true. Roughly equivalent to::
667
666
668
667
def takewhile(predicate, iterable):
669
- # takewhile(lambda x: x<5, [1,4,6,4,1 ]) → 1 4
668
+ # takewhile(lambda x: x<5, [1,4,6,3,8 ]) → 1 4
670
669
for x in iterable:
671
- if predicate(x):
672
- yield x
673
- else:
670
+ if not predicate(x):
674
671
break
672
+ yield x
675
673
676
674
Note, the element that first fails the predicate condition is
677
675
consumed from the input iterator and there is no way to access it.
678
676
This could be an issue if an application wants to further consume the
679
- input iterator after takewhile has been run to exhaustion. To work
677
+ input iterator after * takewhile * has been run to exhaustion. To work
680
678
around this problem, consider using `more-iterools before_and_after()
681
679
<https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.before_and_after> `_
682
680
instead.
@@ -726,10 +724,12 @@ loops that truncate the stream.
726
724
727
725
def zip_longest(*iterables, fillvalue=None):
728
726
# zip_longest('ABCD', 'xy', fillvalue='-') → Ax By C- D-
729
- iterators = [iter(it) for it in iterables]
727
+
728
+ iterators = list(map(iter, iterables))
730
729
num_active = len(iterators)
731
730
if not num_active:
732
731
return
732
+
733
733
while True:
734
734
values = []
735
735
for i, iterator in enumerate(iterators):
0 commit comments