better way to write this function
Arnaud Delobelle
arnodel at googlemail.com
Mon Nov 26 16:33:13 EST 2007
On Nov 26, 8:19 am, Peter Otten <__pete... at web.de> wrote:
[...]
>
> Or build a generator that works with arbitrary iterables:
>
> >>> from itertools import *
> >>> def chunks(items, n):
>
> ... items = iter(items)
> ... while 1:
> ... chunk = list(islice(items, n-1))
> ... chunk.append(items.next())
> ... yield chunk
> ...>>> list(chunks(range(5), 2))
>
> [[0, 1], [2, 3]]
>
> Peter
I was about to send this before I saw your post :)
Well here it is anyway...
Using the fact that StopIteration exceptions fall through list
comprehensions (as opposed to islices):
def chunks(iterable, size):
next = iter(iterable).next
while True:
yield [next() for i in xrange(size)]
--
Arnaud
More information about the Python-list
mailing list