[Python-ideas] itertools.chunks(iterable, size, fill=None)
MRAB
python at mrabarnett.plus.com
Sat Sep 1 18:39:50 CEST 2012
On 01/09/2012 07:27, anatoly techtonik wrote:
> I've run into the necessity of implementing chunks() again. Here is
> the code I've made from scratch.
>
> def chunks(seq, size):
> '''Cut sequence into chunks of given size. If `seq` length is
> not divisible by `size` without reminder, last chunk will
> have length less than size.
>
> >>> list( chunks([1,2,3,4,5,6,7], 3) )
> [[1, 2, 3], [4, 5, 6], [7]]
> '''
> endlen = len(seq)//size
> for i in range(endlen):
> yield [seq[i*size+n] for n in range(size)]
> if len(seq) % size:
> yield seq[endlen*size:]
>
Here's a lazy version:
def chunks(seq, size):
'''Cut sequence into chunks of given size. If `seq` length is
not divisible by `size` without reminder, last chunk will
have length less than size.
>>> list( chunks([1,2,3,4,5,6,7], 3) )
[[1, 2, 3], [4, 5, 6], [7]]
'''
if size < 1:
raise ValueError("chunk size less than 1")
it = iter(seq)
try:
while True:
chunk = []
for _ in range(size):
chunk.append(next(it))
yield chunk
except StopIteration:
if chunk:
yield chunk
More information about the Python-ideas
mailing list