[3.11] Sync the batched() recipe with the 3.12 implementation (GH-98446)

This commit is contained in:
Raymond Hettinger 2022-10-19 09:21:14 -05:00 committed by GitHub
parent 30b9c4d784
commit 07cc997e00
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -887,6 +887,8 @@ which incur interpreter overhead.
def batched(iterable, n): def batched(iterable, n):
"Batch data into lists of length n. The last batch may be shorter." "Batch data into lists of length n. The last batch may be shorter."
# batched('ABCDEFG', 3) --> ABC DEF G # batched('ABCDEFG', 3) --> ABC DEF G
if n < 1:
raise ValueError('n must be at least one')
it = iter(iterable) it = iter(iterable)
while (batch := list(islice(it, n))): while (batch := list(islice(it, n))):
yield batch yield batch
@ -1272,12 +1274,6 @@ which incur interpreter overhead.
[['A', 'B'], ['C', 'D'], ['E', 'F'], ['G']] [['A', 'B'], ['C', 'D'], ['E', 'F'], ['G']]
>>> list(batched('ABCDEFG', 1)) >>> list(batched('ABCDEFG', 1))
[['A'], ['B'], ['C'], ['D'], ['E'], ['F'], ['G']] [['A'], ['B'], ['C'], ['D'], ['E'], ['F'], ['G']]
>>> list(batched('ABCDEFG', 0))
[]
>>> list(batched('ABCDEFG', -1))
Traceback (most recent call last):
...
ValueError: Stop argument for islice() must be None or an integer: 0 <= x <= sys.maxsize.
>>> s = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' >>> s = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> all(list(flatten(batched(s[:n], 5))) == list(s[:n]) for n in range(len(s))) >>> all(list(flatten(batched(s[:n], 5))) == list(s[:n]) for n in range(len(s)))
True True