@@ -775,10 +775,7 @@ which incur interpreter overhead.
775
775
return sum(map(pred, iterable))
776
776
777
777
def pad_none(iterable):
778
- """Returns the sequence elements and then returns None indefinitely.
779
-
780
- Useful for emulating the behavior of the built-in map() function.
781
- """
778
+ "Returns the sequence elements and then returns None indefinitely."
782
779
return chain(iterable, repeat(None))
783
780
784
781
def ncycles(iterable, n):
@@ -860,6 +857,13 @@ which incur interpreter overhead.
860
857
else:
861
858
raise ValueError('Expected fill, strict, or ignore')
862
859
860
+ def batched(iterable, n):
861
+ "Batch data into lists of length n. The last batch may be shorter."
862
+ # batched('ABCDEFG', 3) --> ABC DEF G
863
+ it = iter(iterable)
864
+ while (batch := list(islice(it, n))):
865
+ yield batch
866
+
863
867
def triplewise(iterable):
864
868
"Return overlapping triplets from an iterable"
865
869
# triplewise('ABCDEFG') -> ABC BCD CDE DEF EFG
@@ -1232,6 +1236,36 @@ which incur interpreter overhead.
1232
1236
>>> list (grouper(' abcdefg' , n = 3 , incomplete = ' ignore' ))
1233
1237
[('a', 'b', 'c'), ('d', 'e', 'f')]
1234
1238
1239
+ >>> list (batched(' ABCDEFG' , 3 ))
1240
+ [['A', 'B', 'C'], ['D', 'E', 'F'], ['G']]
1241
+ >>> list (batched(' ABCDEF' , 3 ))
1242
+ [['A', 'B', 'C'], ['D', 'E', 'F']]
1243
+ >>> list (batched(' ABCDE' , 3 ))
1244
+ [['A', 'B', 'C'], ['D', 'E']]
1245
+ >>> list (batched(' ABCD' , 3 ))
1246
+ [['A', 'B', 'C'], ['D']]
1247
+ >>> list (batched(' ABC' , 3 ))
1248
+ [['A', 'B', 'C']]
1249
+ >>> list (batched(' AB' , 3 ))
1250
+ [['A', 'B']]
1251
+ >>> list (batched(' A' , 3 ))
1252
+ [['A']]
1253
+ >>> list (batched(' ' , 3 ))
1254
+ []
1255
+ >>> list (batched(' ABCDEFG' , 2 ))
1256
+ [['A', 'B'], ['C', 'D'], ['E', 'F'], ['G']]
1257
+ >>> list (batched(' ABCDEFG' , 1 ))
1258
+ [['A'], ['B'], ['C'], ['D'], ['E'], ['F'], ['G']]
1259
+ >>> list (batched(' ABCDEFG' , 0 ))
1260
+ []
1261
+ >>> list (batched(' ABCDEFG' , - 1 ))
1262
+ Traceback (most recent call last):
1263
+ ...
1264
+ ValueError: Stop argument for islice() must be None or an integer: 0 <= x <= sys.maxsize.
1265
+ >>> s = ' ABCDEFGHIJKLMNOPQRSTUVWXYZ'
1266
+ >>> all (list (flatten(batched(s[:n], 5 ))) == list (s[:n]) for n in range (len (s)))
1267
+ True
1268
+
1235
1269
>>> list (triplewise(' ABCDEFG' ))
1236
1270
[('A', 'B', 'C'), ('B', 'C', 'D'), ('C', 'D', 'E'), ('D', 'E', 'F'), ('E', 'F', 'G')]
1237
1271
0 commit comments