Re: better way to write this function
- From: Arnaud Delobelle <arnodel@xxxxxxxxxxxxxx>
- Date: Mon, 26 Nov 2007 13:33:13 -0800 (PST)
On Nov 26, 8:19 am, Peter Otten <__pete...@xxxxxx> 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
.
- References:
- better way to write this function
- From: Kelie
- Re: better way to write this function
- From: Peter Otten
- better way to write this function
- Prev by Date: Re: the annoying, verbose self
- Next by Date: Installing Python 3000
- Previous by thread: Re: better way to write this function
- Next by thread: Re: better way to write this function
- Index(es):
Relevant Pages
|