@@ -2394,6 +2394,21 @@ def test_permutations_sizeof(self):
2394
2394
... else:
2395
2395
... return starmap(func, repeat(args, times))
2396
2396
2397
+ >>> def grouper(iterable, n, *, incomplete='fill', fillvalue=None):
2398
+ ... "Collect data into non-overlapping fixed-length chunks or blocks"
2399
+ ... # grouper('ABCDEFG', 3, fillvalue='x') --> ABC DEF Gxx
2400
+ ... # grouper('ABCDEFG', 3, incomplete='strict') --> ABC DEF ValueError
2401
+ ... # grouper('ABCDEFG', 3, incomplete='ignore') --> ABC DEF
2402
+ ... args = [iter(iterable)] * n
2403
+ ... if incomplete == 'fill':
2404
+ ... return zip_longest(*args, fillvalue=fillvalue)
2405
+ ... if incomplete == 'strict':
2406
+ ... return zip(*args, strict=True)
2407
+ ... if incomplete == 'ignore':
2408
+ ... return zip(*args)
2409
+ ... else:
2410
+ ... raise ValueError('Expected fill, strict, or ignore')
2411
+
2397
2412
>>> def triplewise(iterable):
2398
2413
... "Return overlapping triplets from an iterable"
2399
2414
... # pairwise('ABCDEFG') -> ABC BCD CDE DEF EFG
@@ -2411,11 +2426,6 @@ def test_permutations_sizeof(self):
2411
2426
... window.append(x)
2412
2427
... yield tuple(window)
2413
2428
2414
- >>> def grouper(n, iterable, fillvalue=None):
2415
- ... "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
2416
- ... args = [iter(iterable)] * n
2417
- ... return zip_longest(*args, fillvalue=fillvalue)
2418
-
2419
2429
>>> def roundrobin(*iterables):
2420
2430
... "roundrobin('ABC', 'D', 'EF') --> A D E B F C"
2421
2431
... # Recipe credited to George Sakkis
@@ -2584,9 +2594,22 @@ def test_permutations_sizeof(self):
2584
2594
>>> dotproduct([1,2,3], [4,5,6])
2585
2595
32
2586
2596
2587
- >>> list(grouper(3, 'abcdefg', 'x'))
2597
+ >>> list(grouper('abcdefg', 3, fillvalue= 'x'))
2588
2598
[('a', 'b', 'c'), ('d', 'e', 'f'), ('g', 'x', 'x')]
2589
2599
2600
+ >>> it = grouper('abcdefg', 3, incomplete='strict')
2601
+ >>> next(it)
2602
+ ('a', 'b', 'c')
2603
+ >>> next(it)
2604
+ ('d', 'e', 'f')
2605
+ >>> next(it)
2606
+ Traceback (most recent call last):
2607
+ ...
2608
+ ValueError: zip() argument 2 is shorter than argument 1
2609
+
2610
+ >>> list(grouper('abcdefg', n=3, incomplete='ignore'))
2611
+ [('a', 'b', 'c'), ('d', 'e', 'f')]
2612
+
2590
2613
>>> list(triplewise('ABCDEFG'))
2591
2614
[('A', 'B', 'C'), ('B', 'C', 'D'), ('C', 'D', 'E'), ('D', 'E', 'F'), ('E', 'F', 'G')]
2592
2615
0 commit comments