[Python-ideas] itertools.chunks()

Nathan Schneider nathan at cmu.edu
Sat Apr 6 21:06:22 CEST 2013


On Sat, Apr 6, 2013 at 2:53 PM, Giampaolo Rodolà <g.rodola at gmail.com> wrote:

> 2013/4/6 João Bernardo <jbvsmo at gmail.com>:
> > Isn't it just
> >
> >    divmod(total, step)
> >
> > João Bernardo
>
> Not really:
>
> >>> list(chunks(13, 4))
> [4, 4, 4, 1]
> >>> divmod(13, 4)
> (3, 1)
>
>
I think what João means is you can do:

def chunks(total, step):
    a,b = divmod(total,step)
    return [step]*a + [b]

>>> chunks(13,4)
[4, 4, 4, 1]

Or, to avoid necessarily constructing the list all at once:

def chunks(total, step):
    a,b = divmod(total,step)
    return itertools.chain(itertools.repeat(step,a), [b])

>>> list(chunks(13,4))
[4, 4, 4, 1]

Nathan


> Literally chunks() keeps yielding 'step' until 'total' is reached and
> makes sure the last yielded item has the correct remainder.
>
> --- Giampaolo
> https://code.google.com/p/pyftpdlib/
> https://code.google.com/p/psutil/
> https://code.google.com/p/pysendfile/
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20130406/a2f810c1/attachment.html>


More information about the Python-ideas mailing list