getting n items at a time from a generator

Kugutsumen kugutsumen at gmail.com
Thu Dec 27 08:00:27 EST 2007


On Dec 27, 7:24 pm, Terry Jones <te... at jon.es> wrote:
> >>>>> "Kugutsumen" == Kugutsumen  <kugutsu... at gmail.com> writes:
>
> Kugutsumen> On Dec 27, 7:07 pm, Paul Hankin <paul.han... at gmail.com> wrote:
>
> >> On Dec 27, 11:34 am, Kugutsumen <kugutsu... at gmail.com> wrote:
>
> >> > I am relatively new the python language and I am afraid to be missing
> >> > some clever construct or built-in way equivalent to my 'chunk'
> >> > generator below.
>
> Kugutsumen> Thanks, I am going to take a look at itertools.  I prefer the
> Kugutsumen> list version since I need to buffer that chunk in memory at
> Kugutsumen> this point.
>
> Also consider this solution from O'Reilly's Python Cookbook (2nd Ed.) p705
>
>     def chop(iterable, length=2):
>         return izip(*(iter(iterable),) * length)
>
> Terry

Thanks Terry,

However, chop ignores the remainder of the data in the example.

>>> t = (i for i in range(30))
>>> c =chop (t, 7)
>>> for ch in c:
...     print ch
...
(0, 1, 2, 3, 4, 5, 6)
(7, 8, 9, 10, 11, 12, 13)
(14, 15, 16, 17, 18, 19, 20)
(21, 22, 23, 24, 25, 26, 27)

k



More information about the Python-list mailing list