Created
May 20, 2009 07:46
-
-
Save svetlyak40wt/114681 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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