Re: better way to write this function



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

.



Relevant Pages

  • Re: trouble with generators
    ... def records(self, cls): ... yield cls ... It's not quadratic - you add the same B to a.b in each generator run, so the first run shows 3 times the B, then 6, then 9. ...
    (comp.lang.python)
  • Re: Augmented generators?
    ... AFAIK there's no way to have "yield" produce anything other than a ... generator. ... def value: ... dict.iteritemsenumerates tuples for dictionaries, ...
    (comp.lang.python)
  • Re: reseting an iterator
    ... def gen: ... yield open.read ... How would you "easily" reset this generator so that it returns the same ... Why are you assuming that resetting a generator should return the same ...
    (comp.lang.python)
  • Re: Augmented generators?
    ... >> taking advantage of the yield statement in its implementation. ... >You can make an internal function that's a generator with a yield ... This suffers from the same problem as my first go (an exhausted iterator ... def _gen: ...
    (comp.lang.python)
  • Re: hello! first post to clr. Im asking about an attempt at a lazy ruby solution to computing fibona
    ... sum += n ... # create a "lazy stream" that generates the fibonacci sequence ... supply a generator lambda. ... def initialize generator ...
    (comp.lang.ruby)