Skip to content

Instantly share code, notes, and snippets.

@svetlyak40wt
Created May 20, 2009 07:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save svetlyak40wt/114681 to your computer and use it in GitHub Desktop.
Save svetlyak40wt/114681 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
def group_by_n(iter_or_collection, n):
""" This function returns iterator which iterates over tuples by n
>>> rr = 'abcdefghijklmnopqrstuvwxyz'
>>> for i in group_by_n(rr, 3):
... print tuple(i)
('a', 'b', 'c')
('d', 'e', 'f')
('g', 'h', 'i')
('j', 'k', 'l')
('m', 'n', 'o')
('p', 'q', 'r')
('s', 't', 'u')
('v', 'w', 'x')
('y', 'z')
"""
from itertools import groupby, count, izip, imap
return ((item[1] for item in row[1])
for row in
groupby(izip(count(0), iter_or_collection), lambda v: v[0]/n))
if __name__ == '__main__':
import doctest
doctest.testmod()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment