Group by N python generator

Published at 20, May 2009, author art. Tags: python, snippet

Lame and stupid generator to group any iterable's items by N. Just use itertools.izip instead! :)

Comments

Subscribe on this post's comments

permalink

20, May 2009, owner of http://tag.wordaligned.org/ said:

http://docs.python.org/library/functions.html#zip

"The left-to-right evaluation order of the iterables is guaranteed. This makes possible an idiom for clustering a data series into n-length groups using zip([iter(s)]n)"

Use itertools.izip (or Python 3.0!) to generate N-tuples.

permalink

21, May 2009, owner of http://jackdied.blogspot.com/ said:

Please kill this before it gets cut-n-pasted around. What you want is on the itertools docs page. http://docs.python.org/library/itertools.html#module-itertools

    def grouper(n, iterable, fillvalue=None):
            "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
            args = [iter(iterable)] * n
            return izip_longest(fillvalue=fillvalue, *args)

This does less work in general and also works with infinite iterators. And thank you for making me learn a markup language just to post this comment.

permalink

22, May 2009, owner of http://paddy3118.blogspot.com/ said:

from itertools import groupby N = range(10) groupevery = 4 [list(x[1]) for x in groupby(N, lambda x: x // groupevery)] [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9]]

permalink

22, May 2009, art said:

Thanks for your comments guys, you've opened my eyes :)

If you wish to leave comment, please, identify yourself and then come back to this page.